Problem Solving: Matrices with 2-D Arrays
Learn how multi-dimensional arrays can be used in different operations.
We'll cover the following
Column-by column sum
Given a two-dimensional array, calculate the sum of each column.
Sample input
4 3 2 1 5
5 2 5 4 6
1 2 3 5 7
8 9 6 3 2
1 3 5 7 9
Sample output
[19,19,21,20,29]
Let’s discuss how we can solve this problem.
First, let’s make a function sumofAColumn()
in which we have three parameters:
int M[][maxCols]
: The 2-D array that needs to be processed.int ci:
The column indexci
.int rows:
The total number of rows inM
.
To calculate the sum of the ci
th column we need to fix the column to ci
and iterate each row from 0
to rows-1
. We will accumulate each value and return the accumulated sum at the end.
Get hands-on with 1200+ tech skills courses.