View Single Post
Join Date: Mar 2008
Posts: 89
Reputation: bhoot_jb is on a distinguished road 
Solved Threads: 2
bhoot_jb bhoot_jb is offline Offline
Junior Poster in Training

Re: Trouble with loops - Calculate sum of even and odd integers

 
0
  #7
Oct 6th, 2008
Originally Posted by ShadowOfBlood View Post
Nvm, I was going about it wrong. I figured it out. Here's what I have:

  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int even = 0, odd = 0, dig, num;
  9.  
  10. cout << "Please enter a list of numbers (ex. - 12345)" << endl;
  11. cin >> num;
  12.  
  13. while (num > 0)
  14. {
  15. dig = num % 10;
  16. num = num / 10;
  17.  
  18. if(dig % 2 == 0)
  19. even = even + dig;
  20. else
  21. odd = odd + dig;
  22. }
  23.  
  24. cout << "The sum of the even integers is: " << even << endl;
  25. cout << "The sum of the odd integers is: " << odd << endl;
  26.  
  27. return 0;
  28. }

Thanks for the help

what is quite confusing is the 'num' integer.
You said that you are taking input of a list of integers while you have just asked for a single integer.
I assume that you have taken the input of "list of integers" in a single integer 'num' itself, i.e., you have considered the value of 'num' as a list of integers (digit by digit)
if this is what you have assumed, i think this is a wrong approach. You would have rather used an array.
Think upon it.
Bhoot
Reply With Quote