Wednesday, October 7, 2020

Assignment 5. Arrays

  Assignment 5. Arrays

C Array

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.

 

Properties of Array

The array contains the following properties.

 1.       Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.

2.       Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.

3.       Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.

Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of C Array

We can declare an array in the c language in the following way.

data_type array_name[array_size]; 

Now, let us see the example to declare the array.

 int marks[5]; 

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

 

Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index. Consider the following example.

 marks[0]=80;//initialization of array 

marks[1]=60; 

marks[2]=70; 

marks[3]=85; 

marks[4]=75; 

initialization of array in c language

 

C array example

#include<stdio.h> 

int main(){     

int i=0;   

int marks[5];//declaration of array      

marks[0]=80;//initialization of array   

marks[1]=60;   

marks[2]=70;   

marks[3]=85;   

marks[4]=75;   

//traversal of array   

for(i=0;i<5;i++){     

printf("%d \n",marks[i]);   

}//end of for loop    

return 0; 

}   

Output

 

80

60

70

85

75


In the following program, we are using bubble sort method to sort the array in ascending order.

 

#include<stdio.h>   

void main ()   

{   

    int i, j,temp;    

    int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};    

    for(i = 0; i<10; i++)   

    {   

        for(j = i+1; j<10; j++)   

        {   

            if(a[j] > a[i])   

            {   

                temp = a[i];   

                a[i] = a[j];   

                a[j] = temp;    

            }    

        }    

    }    

    printf("Printing Sorted Element List ...\n");   

    for(i = 0; i<10; i++)   

    {   

        printf("%d\n",a[i]);   

    }   

}    


 

Two Dimensional Array in C

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to any number of functions wherever required.

 

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

 

data_type array_name[rows][columns]; 

Consider the following example.

 

 

int twodimen[4][3]; 

Here, 4 is the number of rows, and 3 is the number of columns.

 

Initialization of 2D Array in C

In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two-dimensional array can be declared and defined in the following way.

 

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; 

Two-dimensional array example in C

#include<stdio.h> 

int main(){     

int i=0,j=0;   

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};    

//traversing 2D array   

for(i=0;i<4;i++){   

 for(j=0;j<3;j++){   

   printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);   

 }//end of j   

}//end of i   

return 0; 

}   

Output

 

arr[0][0] = 1

arr[0][1] = 2

arr[0][2] = 3

arr[1][0] = 2

arr[1][1] = 3

arr[1][2] = 4

arr[2][0] = 3

arr[2][1] = 4

arr[2][2] = 5

arr[3][0] = 4

arr[3][1] = 5

arr[3][2] = 6


Assignment 5 

Arrays (1-D and 2-D)

Exercise 1

Objective : To demonstrate use of 1-D arrays and functions.


Set A. Write programs to solve the following problems

1. Write a program to accept n numbers and display the array in the reverse order. Write separate functions to accept and display.

#include <stdio.h>

int cal(int);

int main()

{

   int n;

   printf("Enter the number of elements in array\n");

   scanf("%d", &n);

   cal(n);

}

int cal(int n)

{

    int c, d, a[100], b[100];

   printf("Enter the array elements\n");

   for (c = 0; c < n ; c++)

      scanf("%d", &a[c]);

   for (c = n - 1, d = 0; c >= 0; c--, d++)

      b[d] = a[c];

   for (c = 0; c < n; c++)

      a[c] = b[c];

   printf("Reverse array is\n");

   for (c = 0; c < n; c++)

      printf("%d\n", a[c]);

   return 0;

}


2. Write a function for Linear Search, which accepts an array of n elements and a key as parameters and returns the position of key in the array and -1 if the key is not found. Accept n numbers from the user, store them in an array. Accept the key to be searched and search it using this function. Display appropriate messages.

#include <stdio.h>

int main()

{

 int arr[100],n;

 void accept(int a[100], int n);

 int find(int a[100], int n);

 accept(arr,n);

 find(arr,n);

}

void accept(int array[100], int n)

{

  int  c ;

   printf("Enter the number of elements in array\n");

  scanf("%d", &n);

   printf("Enter %d integer\n", n);

   for (c = 0; c < n; c++)

    scanf("%d", &array[c]);

}

int find(int array[100], int n)

{

 int search,c;

  printf("Enter a number to search\n");

  scanf("%d", &search);

   for (c = 0; c < n; c++)

  {

    if (array[c] == search)

    {

      printf("%d is present at location %d.\n", search, c+1);

      break;

    }

  }

  if (c == n)

    printf("%d isn't present in the array.\n", search);

   return 0;

}


3. Write a function, which accepts an integer array and an integer as parameters and counts the

occurrences of the number in the array.

Example: Input 1 5 2 1 6 3 8 2 9 15 1 30

Number : 1

Output: 1 occurs 3 times

#include <stdio.h>

void main()

{

    int arr[100], freq[100];

    int size, i, j, count;

    printf("Enter size of array: ");

    scanf("%d", &size);

    printf("\nEnter elements in array: ");

    for(i=0; i<size; i++)

    {

        scanf("%d", &arr[i]);

        freq[i] = -1;

    }

    for(i=0; i<size; i++)

    {

        count = 1;

        for(j=i+1; j<size; j++)

        {

            if(arr[i]==arr[j])

            {

                count++;

                freq[j] = 0;

            }

        }

        if(freq[i] != 0)

        {

            freq[i] = count;

        }

    }

    printf("\nFrequency of all elements of array : \n");

    for(i=0; i<size; i++)

    {

        if(freq[i] != 0)

        {

            printf("%d occurs %d times\n", arr[i], freq[i]);

        }

    }

}


4. Write a program to accept n numbers and store all prime numbers in an array called prime.

Display this array.

#include<stdio.h>
int main()
{
     int a[10],n,i,j,c=0,prime[10],t=0;
     printf("Enter Limit : ");
     scanf("%d",&n);
     printf("\nEnter %d Numbers in Array:\n\n",n);
     for(i=0;i<n;i++)
          scanf("%d",&a[i]);
     for(i=0;i<n;i++)
     {
          c=0;
          for(j=2;j<a[i];j++)
          {
               if(a[i]%j==0)
               {
                    c=1;
                    break;
               }
          }
          if(c==0)
          {
               prime[t]=a[i];
               t++;
          }
     }
     printf("\nPrime Numbers in Above Array:\n\n");
     for(i=0;i<t;i++)
     {
          printf(" %d ",prime[i]);
     }
     return 0;
}


Set B. Write programs to solve the following problems

1. Write a function to sort an array of n integers using Bubble sort method. Accept n numbers from

the user, store them in an array and sort them using this function. Display the sorted array.

#include<stdio.h>
#include<stdlib.h>
void bubblesort(int a[],int size);
void main()
{
int a[50],n,i;
printf("\n enter the size of the array");
scanf("%d",&n);
printf("\n enter the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bubblesort(a,n);
printf("\n the sorted array is\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void bubblesort(int a[],int size)
{
int temp,i,j;
for(i=0;i<size;i++)
{
for(j=0;j<size-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}

2. Write a program to accept a decimal number and convert it to binary, octal and hexadecimal.

Write separate functions.

#include<stdio.h>
#include<stdlib.h>
int main()
{
      int num, choice;
      printf("\nEnter Decimal Number:\t");
      scanf("%d", &num);
                printf("\nBinary Value     :\t");
                conversion(num, 2);
                printf("\nOctal Value      :\t");
                conversion(num, 8);
printf("\nHexadecimal Value:\t");
                conversion(num, 16);
      return 0;
}
void conversion(int num, int base)
{
      int remainder = num % base;
      if(num == 0)
      {
            return;
      }
      conversion(num / base, base);
      if(remainder < 10)
      {
            printf("%d", remainder);
      }
      else
      {
            printf("%c", remainder - 10 + 'A' );
      }
}

3. Write a program to find the intersection of the two sets of integers. Store the intersection in

another array.

#include<stdio.h>
#include<math.h>
void main()
{
int i,k=0,x[10],y[10],c[25],j,n,n1,d[25],f=0;
printf("\n how many elements in SET 1:");
scanf("%d",&n);
printf("\n enter 1st SET elements");
for(i=0;i<n;i++)
{
scanf("%d",&x[i]);
}
printf("\n how many elements in set 2:");
scanf("%d",&n1);
printf("\n enter 2st SET elements");
for(i=0;i<n1;i++)
{
scanf("%d",&y[i]);
}
for(i=0;i<n;i++)
{
c[k]=x[i];
k++;
}
for(i=0;i<n;i++)
{
for(j=0;j<n1;j++)
{
if(y[i]==x[j])
break;
}
if(j==n)
{
c[k]=y[i];
k++;
}
}
printf("\n the union set is:{");
for(i=0;i<k;i++)
printf("%d",c[i]);
printf("}\n");
for(j=0;j<n;j++)
{
for(i=0;i<n1;i++)
{
if(y[i]==x[j])
break;
}
if(i!=n1)
{
d[f]=y[i];
f++;
}
}
printf("\n the intersection set is :{");
for(i=0;i<f;i++)
printf("%d",d[i]);
printf("}");
}

4. Write a program to merge two sorted arrays into a third array such that the third array is also in

the sorted order.

a1 10 25 90

a2 9 16 22 26 100


a3 9 10 16 22 25 26 90 100


#include <stdio.h>

int main()

{

    int n1,n2,n3;            //Array Size Declaration

    printf("\nEnter the size of first array ");

    scanf("%d",&n1);

    printf("\nEnter the size of second array ");

    scanf("%d",&n2);

    n3=n1+n2;

    printf("\nEnter the sorted array elements");

    int a[n1],b[n2],c[n3];     //Array Declaration

    for(int i=0;i<n1;i++)      //Array Initialized

    {

       scanf("%d",&a[i]);

       c[i]=a[i];

    }

    int k=n1;

    printf("\nEnter the sorted array elements");

    for(int i=0;i<n2;i++)      //Array Initialized

    {

        scanf("%d",&b[i]);

        c[k]=b[i];

        k++;

    }

    printf("\nThe merged array..\n");

    for(int i=0;i<n3;i++)

    printf("%d ",c[i]);        //Print the merged array

    printf("\nAfter sorting...\n");

    for(int i=0;i<n3;i++)         //Sorting Array

    {

        int temp;

        for(int j=i+1; j<n3 ;j++)

        {

            if(c[i]<c[j])

            {

                temp=c[i];

                c[i]=c[j];

                c[j]=temp;

            }

        }

    }   

    for(int i=0 ; i<n3 ; i++)       //Print the sorted Array 

    {

        printf(" %d ",c[i]);

    }

    return 0;   

}


Exercise 2

Objective : To demonstrate use of 2-D arrays and functions.

Set A . Write C programs for the following problems.

1. Write a program to accept a matrix A of size m X n and store its transpose in matrix B. Display

matrix B. Write separate functions.

#include <stdio.h>
void main()
{
    static int array[10][10];
    int i, j, m, n;

    printf("Enter the order of the matrix \n");
    scanf("%d %d", &m, &n);
    printf("Enter the coeficients of the matrix\n");
    for (i = 0; i < m; ++i)
    {
        for (j = 0; j < n; ++j)
        {
            scanf("%d", &array[i][j]);
        }
    }
    printf("The given matrix is \n");
    for (i = 0; i < m; ++i)
    {
        for (j = 0; j < n; ++j)
        {
            printf(" %d", array[i][j]);
        }
        printf("\n");
    }
    printf("Transpose of matrix is \n");
    for (j = 0; j < n; ++j)
    {
        for (i = 0; i < m; ++i)
        {
            printf(" %d", array[i][j]);
        }
        printf("\n");
    }
}


2. Write a program to add and multiply two matrices. Write separate functions to accept, display,

add and multiply the matrices. Perform necessary checks before adding and multiplying the

matrices.

#include<stdio.h>
void accept(int [10][10],int,int);
void add(int [10][10],int [10][10],int,int);
void mul(int [10][10],int [10][10],int,int,int);
void display(int [10][10],int,int);
main()
{
int a[10][10],b[10][10];
int r1,c1,r2,c2;
printf("For 1st Matrix\n");
printf("Enter no of rows:");
scanf("%d",&r1);
printf("Enter no of columns:");
scanf("%d",&c1);
printf("For 2nd Matrix\n");
printf("Enter no of rows:");
scanf("%d",&r2);
printf("Enter no of columns:");
scanf("%d",&c2);
printf("Enter elements of 1st matrix");
accept(a,r1,c1);
printf("Enter elements of 2nd matrix");
accept(b,r2,c2);
if((r1==r2)&&(c1==c2))
add(a,b,r1,c1);
else
printf("Addition not possible");
if(c1==r2)
mul(a,b,r1,c1,c2);
else
printf("Multiplication not possible");
}
void accept(int a[10][10],int r,int c)
{int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
}
void add(int a[10][10],int b[10][10],int r1,int c1)
{
int i,j;
int d[10][10];
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
d[i][j]=a[i][j]+b[i][j];
}
}
printf("Addition:\n");
display(d,r1,c1);
}
void mul(int a[10][10],int b[10][10],int r1,int c1,int c2)
{
int i,j,v[10][10],k;
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
v[i][j]=0;
for(k=0;k<c1;k++)
{
v[i][j]=v[i][j]+(a[i][k]*b[k][j]);
}
}
}
printf("Multiplication:\n");
display(v,r1,c2);
}
void display(int a[10][10],int r,int c)
{int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}


Set B . Write C programs for the following problems.

1. Write a menu driven program to perform the following operations on a square matrix. Write

separate functions for each option.

i) Check if the matrix is symmetric.

ii) Display the trace of the matrix (sum of diagonal elements).

iii) Check if the matrix is an upper triangular matrix.

iv) Check if the matrix is a lower triangular matrix.

v) Check if it is an identity matrix.


#include<stdio.h>
void sym();
void trace();
void uptri();
void lowtri();
void ide();
void main()
{
int ch;
printf("1.Check if the matrix is symmetric\n 2.Display the trace of the matrix (sum of diagonal elements)\n 3.Check if the matrix is an upper triangular matrix\n 4.Check if the matrix is a lower triangular matrix\n 5.Check if it is an identity matrix\n ");
printf("enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
sym();
break;
case 2:
trace();
break;
case 3:
uptri();
break;
case 4:
lowtri();
break;
case 5:
ide();
break;
}
}
void sym()
{
int m, n, c, d, matrix[10][10], transpose[10][10];

  printf("Enter the number of rows and columns of matrix\n");
  scanf("%d%d", &m, &n);
  printf("Enter elements of the matrix\n");

  for (c = 0; c < m; c++)
    for (d = 0; d < n; d++)
      scanf("%d", &matrix[c][d]);

  for (c = 0; c < m; c++)
    for (d = 0; d < n; d++)
      transpose[d][c] = matrix[c][d];

  if (m == n)
  {
    for (c = 0; c < m; c++)
    {
      for (d = 0; d < m; d++)
      {
        if (matrix[c][d] != transpose[c][d])
          break;
      }
      if (d != m)
        break;
    }
    if (c == m)
      printf("The matrix is symmetric.\n");
    else
      printf("The matrix isn't symmetric.\n");
  }
  else
    printf("The matrix isn't symmetric.\n");
}
void trace()
{
int a[10][10],i,j,sum=0,m,n;
printf("enter the values of m,n");
scanf("%d%d",&m,&n);
printf("enter the elements of matrix a");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(i==j)
sum=sum+a[i][j];
printf("trace of a matrix=%d",sum);
}
void uptri()
{
    int array[10][10];
    int row, col, isUpper,MAX_COLS,MAX_ROWS;
    printf("enter how many row:(row = col):");
    scanf("%d",&MAX_ROWS);
    MAX_COLS=MAX_ROWS;
printf("Enter elements in matrix of size %dx%d: \n", MAX_ROWS, MAX_COLS);
    for(row=0; row<MAX_ROWS; row++)
    {
        for(col=0; col<MAX_COLS; col++)
        {
            scanf("%d", &array[row][col]);
        }
    }
    isUpper = 1;
    for(row=0; row<MAX_ROWS; row++)
    {
        for(col=0; col<MAX_COLS; col++)
        {
            if(col<row && array[row][col]!=0)
            {
                isUpper = 0;
            }
        }
    }
    if(isUpper == 1)
    {
        printf("\nThe matrix is Upper triangular matrix.\n");

        for(row=0; row<MAX_ROWS; row++)
        {
            for(col=0; col<MAX_COLS; col++)
            {
                printf("%d ", array[row][col]);
            }

            printf("\n");
        }
    }
    else
    {
        printf("\nThe matrix is not Upper triangular matrix.");
    }
}
void lowtri()
{
  int array[10][10];
    int row, col, isLower,MAX_COLS,MAX_ROWS;
    printf("enter how many row:(row = col):");
    scanf("%d",&MAX_ROWS);
    MAX_COLS=MAX_ROWS;
    printf("Enter elements in matrix of size %dx%d: \n", MAX_ROWS, MAX_COLS);
    for(row=0; row<MAX_ROWS; row++)
    {
        for(col=0; col<MAX_COLS; col++)
        {
            scanf("%d", &array[row][col]);
        }
    }
    isLower = 1;
    for(row=0; row<MAX_ROWS; row++)
    {
        for(col=0; col<MAX_COLS; col++)
        {
            if(col>row && array[row][col]!=0)
            {
                isLower = 0;
            }
        }
    }
    if(isLower == 1)
    {
        printf("\nMatrix is Lower triangular matrix: \n");
        for(row=0; row<MAX_ROWS; row++)
        {
            for(col=0; col<MAX_COLS; col++)
            {
                printf("%d ", array[row][col]);
            }

            printf("\n");
        }
    }
    else
    {
        printf("\nMatrix is not a Lower triangular matrix");
    }
}
void ide()
{

  int i, j, rows, columns, a[10][10], Flag = 1;
 
  printf("\n Please Enter Number of rows and columns  :  ");
  scanf("%d %d", &i, &j);

  printf("\n Please Enter the Matrix Elements \n");
  for(rows = 0; rows < i; rows++)
   {
    for(columns = 0; columns < j; columns++)
     {
       scanf("%d", &a[rows][columns]);
     }
   }
    
  for(rows = 0; rows < i; rows++)
   {
    for(columns = 0; columns < j; columns++)
     {
     if(a[rows][columns] != 1 && a[columns][rows] != 0)
     {
     Flag = 0;
     break;
}
      }
   }
   if(Flag == 1)
   {
   printf("\n The Matrix that you entered is an Identity Matrix ");
}
else
{
printf("\n The Matrix that you entered is Not an Identity Matrix ");
}
}

2. Write a program to accept an m X n matrix and display an m+1 X n+1 matrix such that the m+1th

row contains the sum of all elements of corresponding row and the n+1th column contains the

sum of elements of the corresponding column.

Example:

    A                         B

1   2    3             1   2   3   6

4   5    6             4   5   6   15

7    8    9             7   8   9   24

                         12  15 18   45


#include <stdio.h>
int main()
{
    int i, j, m, n,p,q,t=0;
    int matrix[10][20],x[10],y[10];
    int sumR, sumC;

    printf("Enter number of rows : ");
    scanf("%d", &m);
    printf("Enter number of columns : ");
    scanf("%d", &n);
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("Enter data in [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    printf("\n");
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }

    printf("\n");
    p=1;
    for (i = 0; i < m; i++)
    {
        sumR = 0;
        for (j = 0; j < n; j++)
        {
            sumR += matrix[i][j];
        }
        x[p]=sumR;
        p++;
    }

    printf("\n");
    q=1;
    for (i = 0; i < n; i++)
    {
        sumC = 0;
        for (j = 0; j < m; j++)
        {
            sumC += matrix[j][i];
        }
        y[q]=sumC;
        q++;
    }
    p=1;
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("%d\t", matrix[i][j]);
        }
        printf("%d",x[p]);
        p++;
        printf("\n");
    }
    for(i=1;i<q;i++)
    {
     t=t+y[i];
        printf("%d\t",y[i]);
}
printf("%d\t",t);
    return 0;
}


No comments:

Post a Comment