Create vector of the sums of the absolute values of the negative elements of the matrix rows

Hi. I need to create a vector using function and can you please check my code and help with it?

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

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
 double a[5][5], x[5], s; int i, j;
 cout << "Input 5x5 matrix\n";
 for (i = 0; i < 5; i++)
  for (j = 0; j < 5; j++)
   a[i][j] = rand() % 18 - 9.;
 for (i = 0; i < 5; i++)
 {
  cout << endl;
  for (j = 0; j < 5; j++)
   cout << a[i][j] << "\t";
 }
 cout << "\nVector:\n";
 for (i = 0; i < 5; i++)
 {
  s = 0;
  for(j=0;j<5;j++)
   if (a[i][j] < 0) { s += fabs(a[i][j]); }
  x[i] = s;
 }
 for (j = 0; j < 5; j++) cout << x[j] << "\n";
 system("pause>>void");
 return 0;
}
Last edited on
Take a look at the for loop that you used to get sum.
1
2
3
4
5
6
7
for (i = 0; i < 5; i++)
 {
  s = 0;
  for(j=0;j<5;j++)
   if (a[i][j] < 0) { s += fabs(a[i][j]); }
  x[i] = s;
 }


More specifically look at the inner for loop.

1
2
  for(j=0;j<5;j++)
   if (a[i][j] < 0) { s += fabs(a[i][j]); }


So your loop is able to add absolute values of negative floating to the sum JUST FINE using the if statement. But what if the the number is not negative? It doesn't get passed through the if condition so it doesn't get added to the sum at all!

Other than that everything seems fine to me. Also if you're going to add a headerfile just for the sake of fabs(), I would rather do something like s += (a[i][j]*-1.0) to avoid having to include math.h
Last edited on
Topic archived. No new replies allowed.