View Single Post
Join Date: Sep 2008
Posts: 21
Reputation: ShadowOfBlood is an unknown quantity at this point 
Solved Threads: 0
ShadowOfBlood ShadowOfBlood is offline Offline
Newbie Poster

Trouble with loops - Calculate sum of even and odd integers

 
0
  #1
Oct 6th, 2008
As a homework assignment, I was asked to write a program in C++ that calculates the sum of the even and odd integers in a list of integers given by the user. I think I'm on the right track, but I can't seem to get my loop right. Here's what I have so far:

  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int num=0, even=0, odd=0, i = 0;
  9. char stop = 'a';
  10.  
  11. cout << "Enter a list of integers followed by the '$' sign: " << endl;
  12. cin >> num;
  13. stop = num;
  14.  
  15. while(stop != '$')
  16. {
  17. if(num % 2 == 0) //If the number is even
  18. even = even + num; //Add it to the current sum of even integers
  19. else if(num % 2 != 0) //if the number is odd
  20. odd = odd + num; //Add it to the current sum of odd integers
  21. else
  22. {
  23. i = 1; //Otherwise, make i equal to 1
  24. }
  25.  
  26. cin >> num;
  27. stop = num;
  28. }
  29.  
  30. if(i == 1)
  31. cout << "Please enter only integers" << endl;
  32. else if(i == 0)
  33. {
  34. cout << "The sum of the even integers is: " << even << endl;
  35. cout << "The sum of the odd integers is: " << odd << endl;
  36. }
  37.  
  38. return 0;
  39. }

Thanks for the help
Last edited by ShadowOfBlood; Oct 6th, 2008 at 3:43 am.
Reply With Quote