- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
- Related Articles
- Count array elements that divide the sum of all other elements in C++
- Minimizing array sum by applying XOR operation on all elements of the array in C++
- Sum all similar elements in one array - JavaScript
- Column sum of elements of 2-D arrays in JavaScript
- How to find the sum of all array elements in R?
- Construct sum-array with sum of elements in given range in C++
- Sum of XOR of sum of all pairs in an array in C++
- How to sum all elements in a nested array? JavaScript
- Compute cartesian product of elements in an array in JavaScript
- Find maximum array sum after making all elements same with repeated subtraction in C++
- Compute the sum of elements of an array which can be null or undefined JavaScript
- Rank of All Elements in an Array using C++
- Compute the median of the masked array elements in Numpy
- Compute the Hyperbolic tangent of the array elements in Python
- Compute the Hyperbolic sine of the array elements in Python

Advertisements