Tuesday, April 26, 2016

2D Arrays



2D Arrays is suitable to hold tabular information for example it can be used to store 4 students degrees in 6 subjects or to represent (mxn) matrix.



Example 1 : (scan matrix) Calculate the summation and average for matrix (3x3).

C code : 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
#include <stdlib.h>


int main()
{

int i,j,sum=0,average ;
int a [3][3] ;

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

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

    }

}


for (i=0;i<3;i++){
    for(j=0;j<3;j++){
sum+=a[i][j];

    }
}

average=sum/6;
printf("sum=%d\n",sum);
printf("average=%d\n",average);

    return 0;
}







Output :





Example 2 : (Print) Calculate The Transpose of 3x3 matrix.

Code 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <stdlib.h>


int main()
{

int i,j ;
int a [3][3]={ {2,3,4},
               {7,8,9},
               {5,2,0} } ;

int t[3][3];

for (i=0;i<3;i++){
    for(j=0;j<3;j++){
t[j][i]=a[i][j];

    }
}

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

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

    printf("\n");
}
    }





Output :




  




Share this

0 Comment to "2D Arrays"

Post a Comment