2D Arrays
2D Arrays
2D Arrays
2D ARRAY DECLARATION
SYNTAX:
Example:
int matrix[3][3];
[0][0] to [rsize-1][colsize-1]
INITIALIZATION
Example:
or
or
{0, 0, 0},
{1, 1, 1}
};
row by row
int matrix[ ][3] = {
{1, 1},
{2, 2, 2}
};
• first dimension size(here row size) is optional, when the array is completely initialized with all
values
• If the values are missing in an initializer, they are automatically set to zero.
110
222
Row 0 1 2 3
Row 1 4 5 6
Row 2 7 8 9
• Two dimensional array are used to represent above matrix or table form of data
• It is an array of one dimensional array • Represented by a single variable name using two
subscripts(rows, columns)
MULTIDIMENSION ARRAYS
• C allows arrays of three or more dimensions. The exact limit is determined by the compiler.
• SYNTAX:
data_type variable_name [s1] [s2] [s3] ….. [sn]; where si is the size of ith dimension
• Examples
int sales[2][5][12];
int sales[2][5][12];//first index denotes year, the second city and the third month
The array sales may represent a sales data of product during the last two years from
Input : [ 8 9 -2
4 -1 -3 ]
Output : 3
#include<stdio.h>
int main()
int a[10][10];
scanf("%d", &a[i][j]);
if(a[i][j] < 0)
count = count + 1;
return 0;
}
Write the program to find the sum of the diagonals of the square matrix
Input : 1 2 3 4
5 6 7 8
9 10 11 12
10 7 6 8
2nd diagonal – 31
#include<stdio.h>
int main()
int i,j,n,d1=0,d2=0,a[5][5];
scanf("%d",&n);
for(i=0;i<n;++i)
for(j=0;j<n;++j) {
scanf("%d",&a[i][j]);
if(i==j)
d1+=a[i][j];
if((i+j)==(n-1))
d2+=a[i][j];
return 0;
}
Write the program which computes and prints the sum of each rows of a 2D Matrix.
Input : [ 8 9 -2
4 -1 -3 ]
1st row – 0
#include <stdio.h>
int main()
int matrix[10][10];
int i, j, r, c;
int sum[10];
scanf("%d", &matrix[i][j]);
sum[i] = 0;
return 0;
}
MCQ
Ans: A
Ans: D
Ans: A
Ans: D
Ans: A
Ans: D
Ans: B
Ans: E
You are transporting some boxes through a tunnel, where each box is a parallelepiped, and is
characterized by its length, width and height. The height of the tunnel 41 feet and the width can be
assumed to be infinite. A box can be carried through the tunnel only if its height is strictly less than
the tunnel’s height. Find the volume of each box that can be successfully transported to the other
end of the tunnel. Note: Boxes cannot be rotated.
Input
4
1 2 40
10 5 41
7 2 42
Output
125
80
Explanation 0
The I box is only 5 feet tall, so it can pass through the tunnel and its volume is 5 x 5 x 5 = 125.
The third box is exactly 41 feet tall, so it cannot pass. The same can be said about the fourth box.
#include<stdio.h>
int main()
int n;
scanf("%d",&n);
int arr[n][3];
for(int i=0;i<n;i++) {
for(int j=0;j<3;j++) {
scanf("%d",&arr[i][j]);
for(int i=0;i<n;i++) {
if(arr[i][2]<41)
printf("%d ",arr[i][0]*arr[i][1]*arr[i][2]);
return 0;