Beezy
Beezy

Reputation: 121

How return true or false from a function in code using a constant array?

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

Answers (4)

Yun Wen
Yun Wen

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

rodolk
rodolk

Reputation: 5907

This code doesn't look good. First you are not using ar (received as parameter) but array a. Second and most important:

  • There is no loop going through all elements of a
  • a[5] is an out-of-bound error. a has 5 elements, from 0 to 4.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

You need to:

  1. Iterate over the elements array.
  2. For each element of the array, check whether the element is odd or even.
  3. If it is odd, accumulate it 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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Several things need to be fixed:

  • You are passing ar to morePos, so there is no need to re-declare the array a
  • You need a loop to go through all elements, not only look at element 5
  • A 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

Related Questions