2D 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.
How to declare 2D Array
The syntax of declaring two dimensional array is very much similar to that of a one dimensional array, given as follows.
int arr[max_rows][max_columns];
Note:
First element of the first row is represented by a[0][0] where the number shown in the first index is the number of that row while the number shown in the second index is the number of the column.
How do we access data in a 2D array
Similar to one dimensional arrays, we can access the individual cells in
a 2D array by using the indices of the cells. There are two indices
attached to a particular cell, one is its row number while the other is
its column number.
We can assign each cell of a 2D array to 0 by using the following code:
for ( int i=0; i<n ;i++)
{
for (int j=0; j<n; j++)
{
a[i][j] = 0;
}
}
Initializing 2D Arrays
The syntax to declare and initialize the 2D array is given as follows.
int arr[2][2] = {0,1,2,3};
Implementation of Array using C Programming Language
#include <stdio.h>
#include<conio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
getch();
}
#include<conio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
getch();
}
Output
No comments:
Post a Comment