c++ - find sum of diagonal elements from given index in 2d array -
i have construct 2d array n,m rows , columns (n & m <= 5), user enters index(location) 2,3 (matrix[2][3]) it's assumed 2 numbers in bounds of matrix. on have find sum of left , right diagonal goes through number, number excluded sum.
so example 2d array myarray[3][3]
*1* 15 *2* 2 *71* 8 *5* 22 *5*
so user enters 1,1 myarray[1][1], in case number 71, sum 1 + 5 + 2 + 5 ... , problem how can find diagonals without going out of bounds.
for left top go: row-- column-- while(row >= 0|| column >= 0) left bottom: row++ colum++ while(row < n || column < m) right top: row-- column++ while(row >= 0 || column < m) right bottom: row++ column-- while(row < n || column >=0)
(this bad written pseudo-code, sorry)
it works fine when enter numbers aren't in top or bottom row, in cases located there program stops.
what have pseudocode. first thought should using &&'s instead of ||'s when determining if location out of bounds or not.
you need sort of way exit in case give bad location. below code wrote out quickly, , seems work @ quick glance - loop on every possible starting location including ones out of bounds.
#include <iostream> const int n = 3; const int m = 4; int matrix[n][m] = { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 } }; int directional_sum(int row, int column, int row_inc, int column_inc) { int sum = 0; if (row < 0 || column < 0 || row >= n || column >= m) return sum; int temp_row = row + row_inc; int temp_column = column + column_inc; while (temp_row >= 0 && temp_column >= 0 && temp_row < n && temp_column < m) { sum += matrix[temp_row][temp_column]; temp_row += row_inc; temp_column += column_inc; } return sum; } int diagonal_sum(int row, int column) { int sum = 0; sum += directional_sum(row, column, 1, 1); sum += directional_sum(row, column, 1, -1); sum += directional_sum(row, column, -1, 1); sum += directional_sum(row, column, -1, -1); return sum; } int main() { (int = -1; <= n; i++) { (int j = -1; j <= m; j++) { std::cout << "sum [" << << ", " << j << "]: " << diagonal_sum(i, j) << std::endl; } } return 0; }
Comments
Post a Comment