# Take and Print Matrix in C

How to take and print matrix in C? How to Print two dimensional or 2D array in C? The 2D array represents a matrix.

To print two dimensional or 2D array in C, we need to use two loops in the nested forms. The loops can be either for loop, while loop, do-while loop, or a combination of them. But understanding the syntax of for loop is easier compared to the while and do-while loop.

In the nested loop, the outer loop represents the row and the inner loop represents the column. The print 2D array, write displaying logic inside the inner loop.

`int arr = {{50,60},{70,80}};`

It is similar to the 2×2 matrix,

``50 6070 80``

Then the array elements are,
`arr = 50;arr = 60;arr = 70;arr = 80;`

## C Program to print 2×2 matrix

``````#include <stdio.h>
int main()
{
// declare and initialize an array
int arr = {{50,60},{70,80}};

// display 2x2 matrix using for loop
printf("The matrix elements are:\n");

// outer loop for row
for(int i=0; i<2; i++) {
// inner loop for column
for(int j=0; j<2; j++) {
printf("%d ", arr[i][j]);
}
printf("\n"); // new line
}

return 0;
}``````

Output:-

The matrix elements are:
50 60
70 80

In this program, we have taken i<2, and j<2 because it contains 2 rows and 2 columns. Here we have hardcoded the 2×2 matrix values because the array was declared and initialized at the same time. Now, let us see another example to take input from the end-user and then display the 2×2 matrix.

## Program to take matrix and display

Here the matrix can be of any size, it is completly depends upon the user input. It can be 2×2, 3×3, 2×3, 3×2, 2×4, 5×3 and e.t.c.

C Program to take matrix and print it

``````#include <stdio.h>
int main()
{
// variables
int row;
int column;

// take row and column size
printf("Ener row size: ");
scanf("%d", &row);
printf("Ener column size: ");
scanf("%d", &column);

// declare array
int arr[row][column];

// take matrix elements as input
printf("Enter elements for %dx%d matrix:\n",
row, column);
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
printf("arr[%d][%d]: ",i,j);
scanf("%d", &arr[i][j]);
}
printf("\n");
}

// display matrix using for loop
printf("The %dx%d matrix elements are:\n",
row, column);
for(int i=0; i<row; i++) {
for(int j=0; j<column; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

return 0;
}``````

Output:-

Ener row size: 2
Ener column size: 2
Enter elements for 2×2 matrix:
arr: 10
arr: 20

arr: 30
arr: 40

The 2×2 matrix elements are:
10 20
30 40

Ener row size: 3
Ener column size: 3
Enter elements for 3×3 matrix:
arr: 1
arr: 2
arr: 3

arr: 4
arr: 5
arr: 6

arr: 7
arr: 8
arr: 9

The 3×3 matrix elements are:
1 2 3
4 5 6
7 8 9

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!