C program to find the sum of all the elements of a matrix

C program to find the sum of all the elements of a matrix

This C program is to find the sum of all the elements of a matrix.For example, for a 2 x 2 matrix, the sum of all elements of the matrix {1,2,3,4} will be equal to 10.

1     2

3    4

 Sum = 1+2+3+4 = 10

Logic

We just keep adding each element of the matrix and store it in the sum variable by using two for loops(to traverse all the elements of the matrix)

Dry Run of the Program

Take input mat[][] and store elements in mat{1,2}{3,4}

Take input ‘row’ and no of rows(row) as 2

Take input ‘col’ and no of columns(col) as 2

Initialize sum=0

1st iteration for(i=0;i<row;i++) i.e. for(i=0;0<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=0+mat[0][0] i.e. sum=0+1  i.e. sum=1

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=1+mat[0][1] i.e. sum=1+2  i.e. sum=3

2nd iteration for(i=1;i<row;i++) i.e. for(i=1;1<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=3+mat[1][0] i.e. sum=3+3  i.e. sum=6

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=6+mat[1][1] i.e. sum=6+4  i.e. sum=10

Now we break out of inner loop and then outer loop.

Hence the sum of all the elements of the matrix[1,2][3,4] would be sum=10

Program

#include<stdio.h>

void main()
{
    int mat[12][12];
    int i,j,row,col,sum=0;
    printf("Enter the number of rows and columns\n");
    scanf("%d%d",&row,&col);
    printf("Enter the elements of the matrix\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            scanf("%d",&mat[i][j]);
        }
    }
    
    printf("The elements in the matrix are\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%d\t",mat[i][j]);
        }
        printf("\n");
    }
    
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            sum=sum+mat[i][j];
        }
    }
    printf("\nSum of all the elements of the matrix = %d",sum);
}

Output

Share Me!