In this tutorial, we will write a Program to access an element in 2D Array in C. Before that, you should have knowledge of the following C programming topics.
Accessing Array Elements
2D Array is of 2 Dimensional, one determines the number of rows and another is for columns.
Example: arr[0][1] refers element belonging to the zeroth row and first column in a 2D array.
- For accessing an elemnt, we need two Subscript variables (i, j).
- i = number of rows.
- j = number of columns.
C Program to access the 2D Array element
#include <stdio.h>
int main()
{
int i, j, arr[3][3];
printf("Enter the element for each row and column:\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("arr[%d][%d] = ", i, j);
scanf("%d", &arr[i][j]);
}
}
//Display array
printf("\nElement present in an Array:\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d\t", arr[i][j]);
}
printf("\n");
}
return (0);
}
Output:
Enter the element for each row and column:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 4
arr[1][1] = 5
arr[1][2] = 6
arr[2][0] = 7
arr[2][1] = 8
arr[2][2] = 9
Element present in an Array:
1 2 3
4 5 6
7 8 9