# Compute sum of all elements in 2 D array in C

CServer Side ProgrammingProgramming

## 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 ;

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,i,j,even=0,odd=0;
printf("Enter elements into the array A :\n");
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\n",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 : 01
A : 02
A : 03
A : 04
A : 10
A : 20
A : 30
A : 40
A : 22
A : 33
A : 44
A : 55
Sum of even elements in array A is: 172
Sum of odd elements in array A is: 92