What's wrong

Hi
Why does my compiler cry?

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
main()
{
      int a[3][2] = {{-3, +7}, {3, 24}, {45, 7} }
      , b[2][4] ={ {-4,  23, 13, 8}, {53, 11, -1, 7} }
      , c[3][4], i, j, k, s = 0;
      
      for(i =0;i<3;++i)
         for(j=0;j<4;++j)
         {
             
            
            for(k=0;k<2;++k)
               s+=a[i][k]*b[k][j];
               c[i][j] = s;                
         }
      }
      
    while(1);
}
Crikey, let me fix that up a bit, it makes me cry too:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>; //so you can have some output

int main() //added int return value - always do this
{
      int a[3][2] = {{-3, +7}, {3, 24}, {45, 7} };  //put 1 variable per line
      int b[2][4] ={ {-4,  23, 13, 8}, {53, 11, -1, 7} };
      int c[3][4], i, j, k, s = 0;
      
      for(i =0;i<3;++i)
         for(j=0;j<4;++j)
         { //delete this brace
            for(k=0;k<2;++k) { //add this brace
               s+=a[i][k]*b[k][j];
               c[i][j] = s;                
            }
      } //delete this brace
      
    while(1); //what is the purpose of an infinite loop here?
return 0;
}


I suggested these changes then realised what a nightmare the for loops are.

Your arrays are all different sizes, so nesting the for loops like that is not going to work. You could have nested loops to deal with the arrays separately .

What is the real world purpose of your program?

Sometimes when I see nightmare programs like this I wonder if the OP is trolling, If not then explain your thinking.
I corrected the code.It had an extra brace as you kindly pointed out:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
main()
{
      
      int a[3][2] = {{-3, +7}, {3, 24}, {45, 7} }
      , b[2][4] ={ {-4,  23, 13, 8}, {53, 11, -1, 7} }
      , c[3][4], i, j, k, s;
      
      for(i =0;i<3;++i)
         for(j=0;j<4;++j)
         {  
              s=0;   
            for(k=0;k<2;++k)
               s+=a[i][k]*b[k][j];
               c[i][j] = s;                
         }
     for(i =0;i<3;++i)
     {    for(j=0;j<4;++j)   
            printf("%d, ", c[i][j]); 
             printf("\n", c[i][j]); 
     }
     while(1);
   
}
      


It's to multiply two arrays.
The problem is why c[1][2] is 15, not 5?
Topic archived. No new replies allowed.