Index « Previous Next »

Question

A matrix is the rectangular array of numbers. Write a program to input and display a matrix of size m x n, where m is the number of rows and n is the number of columns of the matrix.

For example matrix of size 3 x 4 should display like this:

matrix

Source Code

#include <stdio.h>

int main()
{
    int i, j, m, n;
    int matrix[10][20];

    printf("Enter number of rows : ");
    scanf("%d", &m);
    printf("Enter number of columns : ");
    scanf("%d", &n);

    /* Input data in matrix */
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("Enter data in [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    /* Display the matrix */
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output

Enter number of rows : 3
Enter number of columns : 4
Enter data in [0][0]: 10
Enter data in [0][1]: 2
Enter data in [0][2]: 8
Enter data in [0][3]: 11
Enter data in [1][0]: 15
Enter data in [1][1]: 17
Enter data in [1][2]: 9
Enter data in [1][3]: 12
Enter data in [2][0]: 23
Enter data in [2][1]: 21
Enter data in [2][2]: 16
Enter data in [2][3]: 10
10     2       8       11
15     17     9       12
23     21     16     10