Multiply diagonals of 2D array

Write a program in C++ that stores the following elements in a two dimensional
array and prints out the product of all the diagonal elements of the array. Use Nested For
Loops to traverse the array to calculate the product.
The elements of the array are as follows :
12 22 34 45
33 1 2 5
4 98 21 13
3 21 45 11
You should display the product of the following elements: 12 x 1 x 21 x 11 x 3 x 98 x 2 x 45

I'm running into 2 issues. I cant figure out how to choose one set of diagonals, and I also can't figure out how to multiply them. Any help is appreciated. This is my current code, but I've hit a brick wall:

#include <iostream>
using namespace std;
int main(){

const int rows=4;
const int cols=4;
double product=0;

double nums[rows][cols]=
{{12,22,34,45},
{33,1,2,5},
{4,98,21,13},
{3,21,45,11}};


for(int i=0;i<cols;i++)
{
for(int j=0;j<rows;j++)
{
if(i==j){

}
}
}
return 0;
}

Maybe write down all the cols and rows you need to multiply, maybe then you see a bit clearer.

nums [0][0] * nums[1][1] * num[2][2] etc...
You've got most of the code for the upper left to lower right diagonal.
All you need is to compute the product.

1
2
3
if (i==j)
{  product *= nums[i][j];
}


Now, you need to figure out how to get the upper right to lower left diagonal.
Another pair of nested loops works for that, except you want the columns to go from 3 down to 0.

Note that you have the use of rows and cols reversed in your for loops. This doesn't currently have any impact since rows and cols are the same value. You want i (outer loop) to index through your rows, while j (inner loop) indexes through the columns. I find it clearer to use r and c as the index variables for rows and columns.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
Topic archived. No new replies allowed.