8_Two Dimensional Array
8_Two Dimensional Array
Integer constant /
literal
• Example:
int a[3][4];
Row 0 Row 0 Row 0 Row 0
Col 0 Col 1 Col 2 Col 3
Row 1 Row 1 Row 1 Row 1
Col 0 Col 1 Col 2 Col 3
Row 2 Row 2 Row 2 Row 3
Col 0 Col 1 Col 2 Col 3
Initialization of 2-D Array
• int a[2][3] = {21,42,1,94,12,46};
21 42 1
94 12 46
R0 R0 R0 1002 R0 C0
C0 C1 C2 1004 R0 C1
R1 R1 R1 1006 R0 C2
C0 C1 C2
1008 R1 C0
R2 R2 R2
CO C1 C2 1010 R1 C1
R3 R3 R3 1012 R1 C2
C0 C1 C2 1014 R2 C0
1016 R2 C1
1018 R2 C2
1020 R3 C0
1022 R3 C1
1024 R3 C2
Accessing 2-D Array
• A two dimensional array element can be accessed using two indices.
• One for row and other for column. Both the indices start from 0.
• For accessing any item of the array we just specify the array name along
with the row index and column index inside square brackets.
Format:
• Array name [row index][column index]=value/expression
A[4][3]=26; // in the array A, 4th Row and 3rd Column will be assigned with a
value 26
Accessing 2-D Array contd..
int a[2][3]={12,8,7,5,23,14};
12 8 7
printf(“%d”, a[1][2]); 5 23 14
Compile Time Initialization
int a[3][4];
76 878 32 6
scanf(“%d”, &a[0][0]);
12 9 456 56
scanf(“%d”, &a[0][1]); 6 97 79 789
scanf(“%d”, &a[0][2]);
scanf(“%d”, &a[0][3]);
scanf(“%d”, &a[1][0]); For(i=0;i<3;i++)
scanf(“%d”, &a[1][1]); {
scanf(“%d”, &a[1][2]); for(j=0;j<4;j++)
scanf(“%d”, &a[1][3]); {
scanf(“%d”, &a[2][0]); scan(“%d\t”, a[i][j]);
scanf(“%d”, &a[2][1]); }
scanf(“%d”, &a[2][2]); }
scanf(“%d”, &a[2][3]);
Display of Array Elements
printf(“%d”, a[0][2]);
printf(“%d”, a[0][3]);
printf(“%d”, a[1][0]); For(i=0;i<3;i++)
printf(“%d”, a[1][1]); {
printf(“%d”, a[1][2]); for(j=0;j<4;j++)
printf(“%d”, a[1][3]); {
printf(“%d”, a[2][0]); printf(“%d\t”, a[i][j]);
printf(“%d”, a[2][1]); }
printf(“%d”, a[2][2]); printf(“\n”);
printf(“%d”, a[2][3]); } 76 878 32 6
12 9 456 56
13 6 97 79 789
Inputting / displaying values into a two
Dimensional Array
• To input values into a two dimensional array we use a
double loop.
• Example : To input elements into the array List the form
would be:
for(int i=0; i<4; i++) //outer loop for row index
for(int j=0;j<3; j++) //inner loop for column index
scanf(“%d”, &a[i][j]);
The input order will be row wise.
6 4 3
int a[2][3], i, j, sum=0;
for(i=0;i<2;i++) I i<2 J J<3 effect
{ 0 T 0 T Sum=0+5=5
for(j=0;j<3;j++) 1 T Sum=5+2=7
{ 2 T Sum=7+8=15
3 F Out of inner loop
sum=sum + a[i][j]; Print 15
} 1 T 0 T Sum=0+6=6
printf(“Addition of Row 1 T Sum=6+4=10
%d is %d”, i, sum);
2 T Sum=10+3=13
sum=0; 3 F Out of inner loop
} Print 13
2 F exit
Sum of Diagonal Elements
A[0][0]
A[1][1]
A[2][2]
A[3][3]