facebook like button

27 April, 2011

program 36: matrix as 2 dimesional array

The need:
     In most calculations we need matrices. So for a C program to do calculations on matrices it should store the matrix first. This program just takes a matrix as input, stores that and prints back for user.
The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k,m,n;
    int mat[20][25];         //declaration of 2 dimensional array
    printf("Enter the rows..\n");
    scanf("%d",&m);
    printf("Enter the columns..\n");
    scanf("%d",&n);
    printf("Now keep on entering matrix elements.\n\n");
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            printf("Enter element %d%d.\n",i+1,j+1);
            scanf("%d",&k);
            mat[i][j]=k;
        }
    }
    printf("\nThe matrix is\n\n");
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            printf ("%d ",mat[i][j]);
        }
    putchar('\n');
    }
}
--------------------------------------------
The approach: 
This program shows how one can implements 2 dimensional integer array to store a matrix in a C program. Run the program. This program asks you to enter the number of rows and columns of the matrix a and then the matrix and prints that matrix for user. The program uses 2 for loops for taking input from user and 2 loops for printing the output. Here I have assumed that you are very much familiar to nested loops(loop within a loop).

Remarks:
1. In this program you have seen use of 2 dimensional integer array. In C we can have array of any dimension for any data-type but their use is not that common.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply