I'm learning c by myself and I'm currently having trouble making the sum between array values (if >0 else <0).
This is what I've been doing (bilIniziale is my array):
for (int i=0;i<10;i ){
int sum = 0;
if(bilIniziale[i] > 0) {
sum =bilIniziale[i];
}else{
sum =bilIniziale[i];
}
}
I also tried with sum = sum bilIniziale[i];
but no difference.
In the terminal at the moment its only shows the element >0 or <0 but without summing between them; how can I do it?
CodePudding user response:
Since you want the variable sum
to persist outside of the loop you need to move the declaration outside of the loop
int sum = 0;
for (int i=0;i<10;i ){
if(bilIniziale[i] > 0) {
sum =bilIniziale[i];
}else{
sum =bilIniziale[i];
}
}
In your version a new sum
variable gets created and set to zero each time round the loop.
Also as stated in the comment above. The if
statement makes no sense because you do the same thing whether it's true or false. So the above can be simplified
int sum = 0;
for (int i = 0; i < 10; i ) {
sum = bilIniziale[i];
}
EDIT
So it seems the requirement is to make two sums, one of the negative elements the other of the positive elements. So we need two variables, one for each sum. Something like this
int positive_sum = 0;
int negative_sum = 0;
for (int i = 0; i < 10; i ){
if (bilIniziale[i] > 0) {
positive_sum = bilIniziale[i];
} else {
negative_sum = bilIniziale[i];
}
}
CodePudding user response:
With std::accumulate
, you might do:
const int positive_sum =
std::accumulate(std::begin(bilIniziale), std::end(bilIniziale), 0,
[](int acc, int value){ return value > 0 ? acc value : acc; });
const int negative_sum =
std::accumulate(std::begin(bilIniziale), std::end(bilIniziale), 0,
[](int acc, int value){ return value < 0 ? acc value : acc; });
With regular for-range loop, it would be:
int positive_sum = 0;
int negative_sum = 0;
for (auto value : bilIniziale) {
if (value < 0) {
negative_sum = value;
} else { // NO special case for value == 0 as = 0 is noop
positive_sum = value;
}
}