Sum of whole numbers as long as the sum is odd

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>
using namespace 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
}
1
2
3
4
5
while (sum % 2 != 0)
   {
     sum += num;
     cin >> num;
   }


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 

Last edited on
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 
sum whole numbers as long as the sum is odd. (Input: "1 2 5 4" Output: "8 :")


Can you explain what you mean here? How does that output 8? Only 2 of the inputs are odd. And they sum up to 6, am I missunderstanding this?
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.

1 + 2 = 3 (odd)
3 + 5 = 8 (even)
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 


Wow, it was that simple the whole time. Thank you so much.
You're very welcome:)

Happy Coding!
Topic archived. No new replies allowed.