Reputation: 121
I'm suppose to return true or false if the sum of even numbers in an array is greater than the sum of odd numbers in the same array. My program keeps returning true regardless if I change the elements of the array so it can return false. It seems very simple but I cannot seem to figure it out. Any help is appreciated!
My code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool die(const string & msg);
bool morePos(const unsigned ar[], unsigned els);
int main(){
unsigned a[5] = { 7, 7, 7, 2, 4 };
cout << morePos(a, 5) << endl;
}
bool die(const string & msg){
cout << "fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
bool morePos(const unsigned ar[], unsigned els){
unsigned a[5] = { 7, 7, 7, 2, 4 };
unsigned sumOdd = 0;
unsigned sumEven = 0;
if (a[5] % 2 == 0){
sumEven += a[5];
}
if (a[5] % 2 != 0){
sumOdd += a[5];
}
if (sumEven > sumOdd){
return true;
}
else{
return false;
}
}
Upvotes: 1
Views: 781
Reputation: 346
if (a[5] % 2 == 0){
sumEven += a[5];
}
to
for (int i = 0; i < els; ++i)
if (ar[i] % 2 == 0)
sumEven += ar[i];
thanks
Upvotes: 1
Reputation: 5907
This code doesn't look good. First you are not using ar (received as parameter) but array a. Second and most important:
Upvotes: 0
Reputation: 206567
You need to:
sumOdd
. Otherwise, accumulate it in sumEven
.bool morePos(const unsigned ar[], unsigned els){
unsigned sumOdd = 0;
unsigned sumEven = 0;
for ( unsigned i = 0; i < els; ++i )
{
if (a[i] % 2 == 0){
sumEven += a[i];
}
else {
sumOdd += a[i];
}
}
return (sumEven > sumOdd);
}
Upvotes: 1
Reputation: 726489
Several things need to be fixed:
ar
to morePos
, so there is no need to re-declare the array a
5
for
loop would be good for this purpose. Use zero as the beginning index and els
as the limit. Better yet, rename els
as count
or numElements
or something descriptive.Upvotes: 1