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.
The syntax for declaring a 2D array is shown below.
array name[rows][columns] data type;
Consider the following scenario:
int arr[4][3];
Here, 4 represents the number of rows and 3 represents the number of columns.
Note: If the declaration and initialization of the 1D array are done concurrently, we don’t need to mention the array size. This, however, will not work with 2D arrays. We must define at least the array’s second dimension.
storing elements in a matrix and printing them:
#include <stdio.h>
void main ()
{
int z[4][3],i,j;
for (i=0;i<4;i++)
{
for (j=0;j<3;j++)
{
printf("Enter z[%d][%d]: ",i,j);
scanf("%d",&z[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<4;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",z[i][j]);
}
}
}
Output:
Enter z[0][0] = 1
Enter z[0][1] = 2
Enter z[0][2] = 3
Enter z[1][0] = 2
Enter z[1][1] = 3
Enter z[1][2] = 4
Enter z[2][0] = 3
Enter z[2][1] = 4
Enter z[2][2] = 5
Enter z[3][0] = 4
Enter z[3][1] = 5
Enter z[3][2] = 6
printing the elements ....
1 2 3
2 3 4
3 4 5
4 5 6
We’ve made a two-dimensional array of size[4][3], thus the data is stored in a matrix format, where 4 is the number of rows and 3 is the number of columns.
Similarly, we create other multidimensional arrays.
Note: also read about the Passing arguments between functions in C & Arrays in C
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment