Illustrate the use of 2-D arrays in C

A program that fills a two-dimensional array, prints out values, and sums up the elements of the array.

#include <stdio.h>
 
 int main()
 {
    const int M=3,N=4;   // M holds no of rows, N holds no of cols
    int a[M][N];         // Space for elements of a is allocated
    int i,j,Sum=0;
 
    /*Fill the array*/
    for(i=0;i<M;i++)
        for(j=0;j<N;j++)
            a[i][j]=i+j;
 
    /*Print the values in the array*/
    printf("n");
    for(i=0;i<M;i++)
    {
        for(j=0;j<N;j++)
            printf("a[%d][%d]=%d  ",i,j,a[i][j]);
        printf("n");
    }
    /*Calculate the sum of the values of the elements in the array*/
    for(i=0;i<M;i++)
        for(j=0;j<N;j++)
            Sum+=a[i][j];
    printf("The Sum is %d.n",Sum);
    return 0;
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.