Trouble with loops - Calculate sum of even and odd integers
Expand Post »
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:
cout << "Please enter a list of numbers (ex. - 12345)" << endl;
cin >> num;
while(num > 0)
{
dig = num % 10;
num = num / 10;
if(dig % 2 == 0)
even = even + dig;
else
odd = odd + dig;
}
cout << "The sum of the even integers is: " << even << endl;
cout << "The sum of the odd integers is: " << odd << endl;
return0;
}
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.
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.