简体   繁体   中英

Multiplying elements in 2d array

I'm having a problem with the last row of my program. I can't figure out how to multiply the last row by the first row in my program. The multiplication table works by multiplying the first row by the second, second by third, and so on.

    int main() {
int temp;
const int row = 10;
const int col = 5;
int arr[row][col];
int arr2[10][5];

srand(((unsigned)time(0)));

cout << "Original" << endl;

for (int i = 0; i<10; i++) {
    for (int j = 0; j<5; j++) {
        temp = 1 + rand() % 99;
        arr[i][j] = temp;
        int arr2 = arr[i][j];
        cout << setw(4) << arr2<< setw(5) << " | ";

    }
    cout << endl;
}

cout << "\n\nMultiplied rows" << endl;

    for (int i = 0; i<row; i++) {
    for (int j = 0; j < col; j++) {
        if (i < 9)
            arr[i][j] *= arr[i + 1][j];
        else if (i == 9)

        cout << setw(4) << arr[i][j]<< setw(5) << " | ";
    }
    cout << endl;
}

return 0;
}

(it's the last else statement I'm having a problem with) i tried arr[i][j]=arr[1][i]*arr[9][j] but that didn't work

First, the answer to your question. You cant really multiply the last row with the first one because you overwrote it already when arr[i][j] *= arr[i + 1][j]; line executed for i = 0 and j = 0 to 9

The naive solution would be to either store the multiplied numbers in a new array, or don't overwrite the old array and just print the computed values. Even with that, you will have to make other fixes but I am not really going to do your homework for you.

Just FYI, if you are handing this to an instructor they will call out a number of issues, like the fact that you have const int row and col defined but you only use them once .You should just use those variables; so instead of typing things like 10 , 5 and 9 you should type row, col , row -1.

Also the first arr2 variable is unused and the one in the loop could just as easily not be there and your code would be cout << setw(4) << arr[i][j]<< setw(5) << " | "; I could go on but I will leave you to find the rest... Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM