Problem Solving: 2-D Matrix Diagonals Sums
Learn how multi-dimensional arrays can be used in different operations.
Diagonal by diagonal sum
Write a program that does the following:
- Load the matrix.
- Calculate the sum of each diagonal.
- Save each diagonal sum of the 2-D matrix to a 1-D array.
- Display each diagonal sum.
For example, let’s take We have the following matrix and compute the sum of each diagonal.
Computing any diagonal sum
Before we compute all the diagonal summation, let us first make a helping function that should compute any diagonal.
We should have the following prototype:
int diagonalSum(int Matrix[][maxCols], int sri, int sci, int rows, int cols);
In the above,
int Matrix[][maxCols]
holds the original data matrix.int rows, int cols
holds the dimension of the data.int sri, int sci
is the beginning of the diagonal.
Let’s discuss the implementation of diagonalSum()
.
Implementation details
Inside the diagonalSum()
, we will make a loop that starts from the starting index’s row and column and terminates based on the last row or column. To iterate a diagonal, we will increment both row and column by 1 in each iteration. Inside the loop, we should store the sum of each diagonal value in the sum
variable. When the loop terminates, our function will return the sum of one diagonal.
Sample input
Matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Sample output
Matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Diagonal Sum at(2,0):51
Diagonal Sum at(1,0):60
Diagonal Sum at(0,0):65
Diagonal Sum at(0,1):44
Diagonal Sum at(0,2):27
As the output suggests, we should pass the 2-D matrix and its dimensions and the diagonal’s start point to the function. The function should return that diagonal’s sum.
Here is the implementation:
void load2DArray(ifstream &Rdr, int matrix[][MaxCols], int &rows, int &cols);void print2DArray(const char MSG[], int matrix[][MaxCols], int rows, int cols);void print1DArray(const char MSG[], int Array[], int size);// #define MaxRows 100// #define MaxCols 100// Assume we have above implementations availableint diagonalSum(int Matrix[][MaxCols], int sri, int sci, int rows, int cols){int sum=0;for (int r = sri, c = sci; r < rows && c<cols;r++, c++) // each next value in the is at{ // r+1, c+1 index and so onsum += Matrix[r][c]; // bounded by rows and cols (matrix dimension)}return sum;}int main(){int matrix[MaxRows][MaxCols], rows, cols,DiaSumSize;ifstream Rdr("Matrix.txt");load2DArray(Rdr, matrix, rows, cols);print2DArray("Matrix: ", matrix, rows, cols);cout << "Diagonal sum at (0,0):"<<diagonalSum(matrix, 0,0, rows, cols)<<endl;cout << "Diagonal sum at (1,0):"<<diagonalSum(matrix, 1,0, rows, cols)<<endl;cout << "Diagonal sum at (0,1):"<<diagonalSum(matrix, 0,1, rows, cols)<<endl;// Write the code for calculating diagonal sum at (2,0) and (0,2)return 0;}
Instruction: Run the above code. Then, test the diagonal sum for the diagonals anchored at (2,0) and (0,2).
Computing all diagonal sums
Let’s make another function, allDiagonalSum()
, which should receive a matrix, its dimension, and a 1-D array (to store the diagonal sum) with its size. This function will call the diagonalSum()
for each diagonal and store the sum into diaSum[]
.
Implementation details
Inside the function, we will make two loops:
-
The first loop will start from the last row (
rows-1
), and the column will remain 0 for each iteration. Inside the loop, we need to call thediagonalSum()
for each diagonal and store the sum intoDiaSum[]
. This loop will compute the first half of the 2-D matrix. -
We initially set
diaSumSize
to 0. This size will increment by one each time we store a diagonal sum indiaSum[]
. -
The second loop will start from the first column (
c=1
), and the row will remain 0 for each iteration. Inside the loop, we need to call thediagonalSum()
for each diagonal and store the sum intodiaSum[]
. This loop will compute the second half of the 2-D matrix.
Let’s write down the code below:
void allDiagonalSum(int matrix[][MaxCols], int rows, int cols, int diaSum[], int& diaSumSize){diaSumSize = 0;for (int r = rows - 1; r >= 0; r--){diaSum[diaSumSize] = diagonalSum(matrix, r, 0, rows, cols);diaSumSize++;}for (int c = 1; c < cols; c++){diaSum[diaSumSize] = diagonalSum(matrix, 0, c, rows, cols);diaSumSize++;}}
Let's write down the complete code below. Functions revDiagonalSum()
and revAllDiagonalSum()
will be covered in the exercise that follows.
#include <iostream>#include <iomanip>#include <fstream>using namespace std;#define MaxRows 100#define MaxCols 100void load2DArray(ifstream &Rdr, int matrix[][MaxCols], int &rows, int &cols){Rdr >> rows >> cols;for (int r = 0; r < rows; r++){for (int c = 0; c < cols; c++){Rdr >> matrix[r][c];}}}void print2DArray(const char MSG[], int matrix[][MaxCols], int rows, int cols){cout << endl << endl;cout << MSG;cout << endl;for (int r = 0; r < rows; r++){cout << "\t\t";for (int c = 0; c < cols; c++){cout << setw(3) << matrix[r][c];}cout << endl;}}void print1DArray(const char MSG[], int Array[], int size){cout << endl;cout << MSG;for (int i = 0; i < size; i++){cout << setw(3);cout << Array[i];}}int diagonalSum(int Matrix[][MaxCols], int sri, int sci, int rows, int cols){int sum=0;for (int r = sri, c = sci; r < rows && c<cols;r++, c++) // each next value in the is at{ // r+1, c+1 index and so onsum += Matrix[r][c]; // bounded by rows and cols (matrix dimension)}return sum;}void allDiagonalSum(int matrix[][MaxCols], int rows, int cols, int diaSum[], int& diaSumSize){diaSumSize = 0;for (int r = rows - 1; r >= 0; r--){diaSum[diaSumSize] = diagonalSum(matrix, r, 0, rows, cols);diaSumSize++;}for (int c = 1; c < cols; c++){diaSum[diaSumSize] = diagonalSum(matrix, 0, c, rows, cols);diaSumSize++;}}int revDiagonalSum(int Matrix[][MaxCols], int sri, int sci, int rows, int cols){// write code here}void revAllDiagonalSum(int matrix[][MaxCols], int rows, int cols, int diaSum[], int& diaSumSize){// write code here}int main(){int matrix[MaxRows][MaxCols], rows, cols;int matrixDiagonalSum[MaxRows], DiaSumSize;ifstream rdr("Matrix.txt");// STEP 1: Load Matrixload2DArray(rdr, matrix, rows, cols);// STEP 2: Print the Matrixprint2DArray("Matrix:", matrix, rows, cols);// STEP 3: Calculate the sum of each diagonalallDiagonalSum(matrix, rows, cols, matrixDiagonalSum, DiaSumSize);// STEP 4: Print the diagonal sumprint1DArray(" Diagonal Sum: ", matrixDiagonalSum, DiaSumSize);// Write code for reverse diagonalsreturn 0;}
Exercise: Reverse diagonals
We have generated the sum of each diagonal above from the left bottom to the top right. Now just for your practice, try to solve the same problem from the right bottom to the left top.
Write two functions:
int revDiagonalSum(int Matrix[][MaxCols], int sri, int sci, int rows, int cols);
void revAllDiagonalSum(int matrix[][MaxCols], int rows,
int cols, int diaSum[], int& diaSumSize);