something wrong

my first and second array can be displayed perfectly;
but there is something wrong with the third one;
for the third one, i am trying to display the difference between the 2 arrays after subtraction;
the numbers keep coming up wrong


#include <stdio.h>
int main()
{
#define rows 3
#define columns 3
int a, b, c, d, i, j;
int first [rows][columns] = {15,13,11,11,9,7,7,5,4};
int second [rows][columns] = {12,10,8,8,6,4,4,2,1};
int diff [rows][columns] = first [rows][columns] - second [rows][columns];

printf("The first matrix is:");
for ( a = 0; a < rows; a++)
{
printf("\n");
for (b = 0; b < columns; b++)
printf(" %2d", first [a][b]);
}

printf("\nThe second matrix is:");
for ( c = 0; c < rows; c++)
{
printf("\n");
for (d = 0; d < columns; d++)
printf(" %2d", second [c][d]);
}

printf("\nThe difference of matrices above are:");
for ( i = 0; i < rows; i++)
{
printf("\n");
for (j = 0; j <columns; j++)
printf("%5d", diff [i][j]);

}
return 0;
}
@Limitless98

Yeah, it would be great if getting the differences into an array, worked like that, but sadly, it doesn't.
You have to create a loop and subtract each array element.
1
2
3
4
5
6
7
8
int diff [rows][columns];
for(a=0;a:rows;a++)
{
 for(b=0;b<columns;b++)
  {
   diff [a][b] = first [a][b] - second [a][b];
  }
}

That should take care of it.
@whitenite1

oh ok!!
yeah i switch it up, just had to loop the difference like you said. It would be nice if it worked like i thought it would :)

thanks a lot mate!!
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
29
30
31
#include <iostream>
#include <iomanip>
#include <valarray>
using namespace std;

const int rows = 3;
const int cols = 3;

void printMatrix( const char *prompt, const valarray<int> &matrix )
{
   cout << prompt << '\n';
   for ( int r = 0; r < rows; r++ )
   {
      for ( int c = 0; c < cols; c++ ) cout << setw( 3 ) << matrix[r*cols+c];
      cout << '\n';
   }
   cout << '\n';
}


int main()
{
   valarray<int> first { 15, 13, 11, 11, 9, 7, 7, 5, 4 };
   valarray<int> second{ 12, 10,  8,  8, 6, 4, 4, 2, 1 };

   valarray<int> diff = first - second;                     // <=========

   printMatrix( "The first matrix is" , first  );
   printMatrix( "The second matrix is", second );
   printMatrix( "The difference is"   , diff   );
}
The first matrix is
 15 13 11
 11  9  7
  7  5  4

The second matrix is
 12 10  8
  8  6  4
  4  2  1

The difference is
  3  3  3
  3  3  3
  3  3  3
Topic archived. No new replies allowed.