Tyler Kelly
Tyler Kelly

Reputation: 574

How to add up a certain group of number in an array?

Hey so I have function that needs to add up a certain number of even numbers in an array based off user input. Here's my approach so far:

function call:

cout << "The sum of the first " << userSum << " even numbers is: " << 
SumEvens(list,   SIZE,   userSum);

function definition:

int SumEvens(int arr[], const int size, int evensAdd)
{
    int sum = 0;
    for (int i = 0; i <= size; i++){       
        for (int j = 0; j <= evensAdd; j++){
            if (arr[i] % 2 == 0)
                sum += arr[i];
        } 
   }
return sum;
}

I'm Not sure if i need the double for loop here, but it seems necessary so that i can go through every number and then only select the ones that i need.

Now whenever I run this program and tell it to add up the numbers it spits out garbage, so I was seeing if you guys could point out any glaring flaws in the code. Thanks!

Upvotes: 0

Views: 746

Answers (1)

Jay
Jay

Reputation: 2686

Your implementation is incorrect:

int SumEvens(int arr[], const int size, int evensAdd)
{
   for(int i= 0; i < size; i++){
     std::cout << arr[i] << " ";
  }
  std::cout << std::endl;
  std::cout << size << " " << evensAdd << std::endl;



  int sum = 0;
  for (int i = 0; i <= size; i++){       
         if(evensAdd==0) return sum
         if (arr[i] % 2 == 0){
              sum += arr[i];
              evensAdd--;
         }
      } 
  }
return sum;
}

This doesn't break on evenAdd > size

Upvotes: 1

Related Questions