Compute sum of all elements in 2 D array in C


Problem

Calculate the sum of all elements of a two-dimensional array by using run-time initialization.

Solution

Two-dimensional Array is used in situations where a table of values have to be stored (or) in matrices applications

The syntax is as follows −

datatype array_ name [rowsize] [column size];

For example, int a[4] [4];

Number of elements in an array = rowsize *columnsize = 4*4 = 16

Example

Following is the C program to calculate the sum of all elements of a two-dimensional array by using run-time initialization −

 Live Demo

#include<stdio.h>
void main(){
   //Declaring array and variables//
   int A[4][3],i,j,even=0,odd=0;
   //Reading elements into the array//
   printf("Enter elements into the array A :
");    for(i=0;i<4;i++){       for(j=0;j<3;j++){          printf("A[%d][%d] : ",i,j);          scanf("%d",&A[i][j]);       }    }    //Calculating sum of even and odd elements within the array using for loop//    for(i=0;i<4;i++){       for(j=0;j<3;j++){          if((A[i][j])%2==0){             even = even+A[i][j];          }          else{             odd = odd+A[i][j];          }       }    }    printf("Sum of even elements in array A is : %d
",even);    printf("Sum of odd elements in array A is : %d",odd); }

Output

When the above program is executed, it produces the following result −

Enter elements into the array A:
A[0][0] : 01
A[0][1] : 02
A[0][2] : 03
A[1][0] : 04
A[1][1] : 10
A[1][2] : 20
A[2][0] : 30
A[2][1] : 40
A[2][2] : 22
A[3][0] : 33
A[3][1] : 44
A[3][2] : 55
Sum of even elements in array A is: 172
Sum of odd elements in array A is: 92

Advertisements