Multiplying arrays

Apr 15, 2013 at 12:53am
I am trying to multiply my two arrays togeth as arguments, but I keep getting 0 as my answer. Im guessing the error is in my equation. Any help would be appreciated. Thanks.

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
26
27
28
#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;

float a[10][10], b[10][10], c[10][10];
void array();

int main(int argc, char* argv[]){
        a[10][10]=atof(argv[1]);
        b[10][10]=atof(argv[2]);

        array();

return 0;
}

void array(){
        int i, j, x;

        for(int i = 0; i < 10; i++){
        for(int j = 0; j < 10; j++){
        for(int x = 0; x < 10; x++)
        c[i][j] = a[i][x] * b[x][j];
                }
        }
        cout << "multiplication: " << c[i][j] << endl;
}
Apr 15, 2013 at 3:17am
remove line 23 and change line 24 to c[i][j] = a[i][j] * b[i][j];

E: if you were planning on using the varaibles on line 19, you messed it up by declaring them again in the for-loops. Remove the int in the for-loop and try again.
Last edited on Apr 15, 2013 at 3:20am
Apr 15, 2013 at 6:35am
I have t disagree with Smac89. The array() does matrix multiplication correctly. Declaring variables twice is an error.

However, array() does print only one number, and from cell that does not exists. By the time of cout, i=10 and j=10. Valid indices for these three matrices are 0..9.

Same error in main. a[10][10] and b[10][10] do not exists. Arrays a and b are never initialized, so the content of c is undefined as well.

Edit: Embarrassing. Trust fun2code.
Last edited on Apr 15, 2013 at 7:55am
Apr 15, 2013 at 7:18am
closed account (D80DSL3A)
The array() does matrix multiplication correctly.

Well...almost.
Shouldn't it be:
1
2
3
4
5
6
7
        for(int i = 0; i < 10; i++){
        for(int j = 0; j < 10; j++){
        c[i][j] = 0;// in case c has non-zero element values
        for(int x = 0; x < 10; x++)
        c[i][j] += a[i][x] * b[x][j];// note += here, for summing over the products
                }
        }

The i,j used on line 27 are the uninitialized variables declared on line 19 so their values are unpredictable. The i,j declared in the for loops are out of scope.

If you want to display the 2D array c then this may work better:
1
2
3
4
5
6
7
8
9
10
11
for(int i = 0; i < 10; i++)
{
    for(int j = 0; j < 10; j++)
    {
        c[i][j] = 0;
        for(int x = 0; x < 10; x++)
            c[i][j] += a[i][x] * b[x][j];
        cout << c[i][j] << ' ';// output each row with a space between values
    }
    cout << endl;// newline for next row
}
Last edited on Apr 15, 2013 at 7:26am
Topic archived. No new replies allowed.