Multi Dimensional Array
An array having more than one subscript or dimension is known as multi dimensional array.
i.e.: int arr[3][3].
Multi dimensional arrays are also known as arrays of arrays or matrix.
Syntax - Multi Dimensional Array
In C, Multi-Dimensional arrays can be declared as follows:
Syntax:
Datatype var_name[size1][size2][size3]......................[size n];
So, in the same way, we can declare the 2-D array as:
1. Two Dimensional array requires two subscript variables
2. In the following syntax size1 represents no of rows whereas size2 represents no of columns.
Syntax:
data-type varname [size1][size2];
e.g. : int c[2][4];
So, in the same way, we can declare the 3-D array as:
Syntax:
Datatype var_name[size1][size2][size3];
e.g. : int c[2][3][4];
Two-dimensional array program :-
Example 1: Sum of two matrices
// C program to find the sum of two matrices of order 2*2
#include <stdio.h>
Void main()
{
int i,j;
float a[2][2], b[2][2], result[2][2];
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n");
for ( i = 0; i < 2; ++i)
for ( j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
// Taking input using nested for loop
printf("Enter elements of 2nd matrix\n");
for (i = 0; i < 2; ++i)
for ( j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
// adding corresponding elements of two arrays
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}
// Displaying the sum
printf("\nSum Of Matrix\n");
for ( i = 0; i < 2; ++i)
for ( j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);
if (j == 1)
printf("\n");
}
}
OUTPUT :-
Enter elements of 1st matrix
Enter a11: 1
Enter a12: 2
Enter a21: 3
Enter a22: 4
Enter elements of 2nd matrix
Enter b11: 2.2
Enter b12: 3
Enter b21: 3.5
Enter b22: 5
Sum Of Matrix
3.2 5.0
6.5 9.0
Program File:(click the following .c file to get the program file)
Three-dimensional array program :-
Example 2: Three-dimensional array
// C Program to store and print 12 values entered by the user
#include <stdio.h>
int main() {
int test[2][3][2];
int i,j,k;
printf("Enter 12 values: \n");
for ( i = 0; i < 2; ++i) {
for ( j = 0; j < 3; ++j) {
for ( k = 0; k < 2; ++k) {
scanf("%d", &test[i][j][k]);
}
}
}
// Printing values with proper index.
printf("\nDisplaying values:\n");
for ( i = 0; i < 2; ++i) {
for ( j = 0; j < 3; ++j) {
for ( k = 0; k < 2; ++k) {
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
}
OUTPUT:-
Enter 12 values:
1 3 8 2 3 4 6 5 9 6 10 12
Displaying values:
test[0][0][0] = 1
test[0][0][1] = 3
test[0][1][0] = 8
test[0][1][1] = 2
test[0][2][0] = 3
test[0][2][1] = 4
test[1][0][0] = 6
test[1][0][1] = 5
test[1][1][0] = 9
test[1][1][1] = 6
test[1][2][0] = 10
test[1][2][1] = 12
Program File:(click the following .c file to get the program file)
Comments
Post a Comment