2D Array Explained Using Matrix
2D Array Explained
Let's create an array that has 2 dimensions like a matrix.
Now let's give it some elements.
Let's say int matrix[5][5] = {
Let's create an array that has 2 dimensions like a matrix.
Now let's give it some elements.
Let's say int matrix[5][5] = {
4, 6, 25, 88, 5,
34, 5, 300, 4, 65,
78, 43, 11, 90, 125,
98, 585, 12, 63, 21,
45, 35, 9, 5, 1
};
Now, we will see how to access the elements in the array. To do that we need to use nested for loop.
Let's initialize two values i and j.
So,
int i,j; // Here i represents row and j represents column.
That means when i=0 and j=0, it gets the first element from the matrix i.e 4 and when i=0 and j=1 it gets second element 6 and so on...
Now let's write whole C code to access the elements inside the array matrix.
#include<stdio.h>
int main()
{
int i,j,sum;
int array[5][5]={
4, 6, 25, 88, 5,
34, 5, 300, 4, 65,
78, 43, 11, 90, 125,
98, 585, 12, 63, 21,
45, 35, 9, 5, 1
};
for(i=0; i<5;i++) //There are 5 rows
{
for(j=0;j<5;j++) //There are 5 columns
{
printf("%d\n"" ",array[i][j]);
}
}
NOTE:
When you run it, i gets the value 0 and j also gets 0 and prints array[0][0] i.e 4. It runs again but this time i gets 0 and j=1 because it returns to second for loop and gets the value array[0][1] i.e 6 and so on.
Comments
Post a Comment