Home »
C programs »
C two-dimensional arrays programs
C Program to read and print a RxC Matrix, R and C must be input by User
This program will read a two dimensional array (Matrix), number of rows (R) and number of columns (C) will be read through the User.
C Program to read and print a RxC Matrix, R and C must be input by User
#include <stdio.h>
#define MAXROW 10
#define MAXCOL 10
int main()
{
int matrix[MAXROW][MAXCOL];
int i,j,r,c;
printf("Enter number of Rows :");
scanf("%d",&r);
printf("Enter number of Cols :");
scanf("%d",&c);
printf("\nEnter matrix elements :\n");
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
}
printf("\nMatrix is :\n");
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
printf("%d\t",matrix[i][j]);
}
printf("\n"); /*new line after row elements*/
}
return 0;
}
Output
Enter number of Rows :3
Enter number of Cols :3
Enter matrix elements :
Enter element [1,1] : 1
Enter element [1,2] : 1
Enter element [1,3] : 1
Enter element [2,1] : 2
Enter element [2,2] : 2
Enter element [2,3] : 2
Enter element [3,1] : 3
Enter element [3,2] : 3
Enter element [3,3] : 3
Matrix is :
1 1 1
2 2 2
3 3 3
Read a Matrix
Use the following code to read a matrix of R x C, where R is the number or rows and C is the number of columns.
printf("\nEnter matrix elements :\n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
printf("Enter element [%d,%d] : ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
Print a Matrix
Use the following code to print a matrix of R x C, where R is the number or rows and C is the number of columns.
printf("\nMatrix is :\n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n"); /*new line after row elements*/
}
C Two-dimensional Arrays Programs »