3 Replies - 9179 Views - Last Post: 10 November 2008 - 09:53 PM Rate Topic: -----

#1 EricFG  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Sum of the even numbers in an array?

Posted 10 November 2008 - 09:42 PM

I am trying to sum up the even numbers in my array, but I am not sure what I am doing wrong. I know I need to use "%2" somewhere, but am completely lost. I searched the forums, but all examples were in C++ and not C. Any help would be appreciated. Thanks.

void sum(const int array[], int count)
 
{
 
  int i;
  int sum = 0;
 
  for (i = 0; i < count; i++){
	if(i % 2 == count)
   sum = sum  + array[i];
  
}
  printf("The sum of the even numbers in the array is - %d",sum);
  printf("\n\n");
   
}


This post has been edited by EricFG: 10 November 2008 - 09:44 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Sum of the even numbers in an array?

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3093
  • View blog
  • Posts: 19,139
  • Joined: 14-September 07

Re: Sum of the even numbers in an array?

Posted 10 November 2008 - 09:45 PM

The question is:

do you want to sum up the numbers located at the even subscripts in your array?

or

do you want to add all numbers that are even in your array?

First method:

//stuff

for (int i = 0; i < count; i++)
{
      if (i%2 == 0)
          sum += arr[i];
}



second

//stuff
for(int i = 0; i < count; i++)
{
      if (arr[i] %2 == 0)
             sum += arr[i];
}



Hope that helps :)
Was This Post Helpful? 0
  • +
  • -

#3 GWatt  Icon User is offline

  • member icon

Reputation: 264
  • View blog
  • Posts: 3,059
  • Joined: 01-December 05

Re: Sum of the even numbers in an array?

Posted 10 November 2008 - 09:45 PM

Your if statement is almost right, but instead of
if (i % 2 == count) you want if (array[i] % 2 == 0)

The % operator gives the remainder of the the left side divided by the right side, and when you divide an even number by 2 the remainder is zero.

edit:
and KYA beat me to the punch

This post has been edited by GWatt: 10 November 2008 - 09:46 PM

Was This Post Helpful? 0
  • +
  • -

#4 EricFG  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Re: Sum of the even numbers in an array?

Posted 10 November 2008 - 09:53 PM

thanks so much for the help, been staring at it for hours...such a simple fix.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1