...
/Solution Review: Add Main Diagonal Elements in a Matrix
Solution Review: Add Main Diagonal Elements in a Matrix
Let's go over the solution review of the challenge given in the previous lesson.
We'll cover the following...
Solution #
Press the RUN button and see the output!
Press + to interact
#include <iostream>using namespace std;// add_diagonal functionint add_diagonal(int arr[3][3], int row, int col) {// Initialize sumint sum = 0;// Outer loop to traverse rows in a 2D arrayfor (int i = 0; i < row; i++) {// Inner loop to traverse values in each rowfor (int j = 0; j < col; j++) {// Check if row index is equal to column indexif (i == j) {// Add element at row index i and column index j in sumsum = sum + arr[i][j];}}}return sum;}// print_array functionvoid print_array (int arr[3][3], int row, int column){// Outer loopfor (int i = 0; i < row; i++) {// Inner loopfor (int j = 0; j < column; j++) {cout << arr[i][j] << " ";}cout << endl;}}// main functionint main() {// Declare variableint result;// Initialize 2D arrayint arr[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};// Call print_array functionprint_array(arr,3,3);// Call add_diagonal function and store your output in resultresult = add_diagonal(arr,3,3);// Print the value of resultcout << "sum = " << result ;return 0;}