Two dimensional arrays in C

Previous
Next

Two dimensional arrays:

  • Two dimensional arrays are used to store and process the data which is in the form of rows and columns.
  • Generally we process the array elements using loops.
  • To process two dimensional array, we use 2 loops.
  • Outer loop represents, number of rows and Inner loop represents number of columns.

Syntax:

      Datatype  identity[row_size][column_size];

Ex:

      int  arr[3][3];

  • When the number of rows are “m” and number of columns are “n”, we can store total “m*n” elements.
  • The memory representation as follows:
  • We can declare the array either local or global.
  • Local array initializes with garbage values.
  • We can display the elements using loops.
#include<stdio.h>
int main()
{
	int arr[3][3], i, j;
	
	printf("Array elements are : \n");
	for(i=0 ; i<3 ; i++)
	{
		for(j=0 ; j<3 ; j++)
		{
			printf("%d \t", arr[i][j]);
		}
		printf("\n");
	}
	return 0;	
}
  • We can assign values directly using assignment operator.
  • The elements will store into array in row wise.
#include<stdio.h>
int main()
{
	int arr[3][3] = {10,20,30,40,50,60,70, 80,90}, i, j;
	printf("Array elements are : \n");
	for(i=0 ; i<3 ; i++)
	{
		for(j=0 ; j<3 ; j++)
		{
			printf("%d \t", arr[i][j]);
		}
		printf("\n");
	}
	return 0;	
}

We can also assign values row wise as follows:

#include<stdio.h>
int main()
{
	int arr[3][3] = {{10}, {20,30}, {0,40}}, i, j;
	printf("Array elements are : \n");
	for(i=0 ; i<3 ; i++)
	{
		for(j=0 ; j<3 ; j++)
		{
			printf("%d \t", arr[i][j]);
		}
		printf("\n");
	}
	return 0;	
}

Reading elements into array:

#include<stdio.h>
int arr[2][2];
int main()
{
	int i, j;
	printf("Enter array elements : \n");
	for(i=0 ; i<2 ; i++)
	{
		for(j=0 ; j<2 ; j++)
		{
			scanf("%d", &arr[i][j]);
		}
		printf("\n");
	}
	
	printf("Array elements are : \n");
	for(i=0 ; i<2 ; i++)
	{
		for(j=0 ; j<2 ; j++)
		{
			printf("%d \t", arr[i][j]);
		}
		printf("\n");
	}
	return 0;	
}

Read elements by reading the size of array:

#include<stdio.h>
int arr[10][10];
int main()
{
	int m, n, i, j;
	printf("Enter row size : ");
	scanf("%d", &m);
	
	printf("Enter column size : ");
	scanf("%d", &n);
	
	printf("Enter %d elements into %dx%d array : \n", m*n, m, n);
	for(i=0 ; i<m ; i++)
	{
		for(j=0 ; j<n ; j++)
		{
			printf("Enter arr[%d][%d] location element : ", i, j);
			scanf("%d", &arr[i][j]);
		}
		printf("\n");
	}
	
	printf("%dx%d Array elements are : \n", m, n);
	for(i=0 ; i<m ; i++)
	{
		for(j=0 ; j<n ; j++)
		{
			printf("%d \t", arr[i][j]);
		}
		printf("\n");
	}
	return 0;	
}
Previous
Next

Add Comment

Courses Enquiry Form