Can someone please tell me what's wrong with this program? I'm supposed to create a program that will read and sum whole numbers as long as the sum is odd. (Input: "1 2 5 4" Output: "8 :")
When I run it, no matter what numbers I enter, I get "0 :"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int num, sum;
cin >> num;
while (sum % 2 != 0)
{
sum += num;
cin >> num;
}
cout << sum << ' '; //DO NOT MODIFY, MOVE or DELETE
cout << ':' << endl; return 0; //DO NOT MODIFY, MOVE or DELETE
}
You have to initialize sum first.
And your program never enters the loop.
You want this - while (num% 2 != 0) // num not sum.
1 2 3 4 5 6 7 8 9 10 11
int num, sum = 0;
cin >> num;
while (num % 2 != 0)
{
sum += num;
cin >> num;
}
cout << sum << ' '; //DO NOT MODIFY, MOVE or DELETE
cout << ':' << endl; //DO NOT MODIFY, MOVE or DELETE
Ok, I made those changes and I understand why it should work, but I'm still getting the wrong output. This time I get "1 :".
1 2 3 4 5 6 7 8 9 10 11
int num, sum = 0;
cin >> num;
while (num % 2 != 0)
{
sum += num;
cin >> num;
}
cout << sum << ' '; //DO NOT MODIFY, MOVE or DELETE
cout << ':' << endl; //DO NOT MODIFY, MOVE or DELETE
I think the question is trying to say that you have to keep reading inputs and adding them together as long the sum is odd, then stop reading once you have an even sum and print the sum.
So with the sample input, the program should stop reading inputs after 5 is added since it creates an even sum.
Oh in that case, thats easy. You're using the wrong loop. It should be a do-while loop.
1 2 3 4 5 6 7 8 9 10 11
int num, sum = 0;
do
{
cin >> num;
sum += num;
} while (sum % 2 != 0);
cout << sum << ' '; //DO NOT MODIFY, MOVE or DELETE
cout << ':' << endl; //DO NOT MODIFY, MOVE or DELETE