C

How To Print a 2D Array in C

In this tutorial, we are going to see how to print a two dimensional(2D) array in C. In the following program, we ask the user to enter the size of the rows and columns of the array, and then enter the elements of the array. To display all the elements of the array in two dimensions (row by column), we are going to use two ‘for’ loops.
 

How To Print a 2D Array in C
#include <stdio.h>

void main()
{
  int arr[10][10];
  int i, j, row, col;
  
  printf("Enter the number of rows (max 10): ");
  scanf("%d",&row);
  
  printf("Enter the number of columns (max 10): ");
  scanf("%d",&col);
  
  printf("Enter the %d array elements: ",row*col);
  for(i = 0; i < row; i++)
  {
    for(j = 0; j < col; j++)
    {
      scanf("%d",&arr[i][j]);
    }
  }
  printf("2D array = \n");
  for(i=0; i < row; i++)
  {
    for(j = 0; j < col; j++)
    {
      printf("%4d",arr[i][j]);
    }
    printf("\n");
  }
}

Output:

Enter the number of rows (max 10): 4
Enter the number of columns (max 10): 4
Enter the 16 array elements: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16         
2D array = 
   1   2   3   4
   5   6   7   8
   9  10  11  12
  13  14  15  16

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *