Sum of Odds

I need help figuring out the formula for this code. The user inputs a list of numbers, then I need the program to compute the sum of all odd numbers I typed in. Using a while loop, the loop ends when "-1" in input. This is what I have so far, but I know it is off. No numbers give a sum as a result, the output is always 0.

This would be a correct output from the compiler:

Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: 7
Enter a number: -1

The sum of the odd numbers is 15.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
using namespace std;

int main( )
{
    int count = 0;
    int num;
    
    cout << "Enter a number: ";
    cin >> num;
    
    while (num != -1)
    {
        cout << "Enter a number: ";
        cin >> num;
    }
    if (num % 2 != 0)
    {
        int sum = sum + num;
    }
    
    cout << "The sum of the odd numbers is " << sum << endl;
}
Last edited on
first, a good habit to initialize values.
int num = 0; //even if you overwrite it later, its good habit.

second, this is why we have do-while:

do
{
cin >> num;
etc
} while(num != -1);

to avoid the awkward pre-while out of loop repeated inner loop code.
There are other ways to avoid it also; you can ugly a for loop to do anything, but do-while is correct here.

now your real issue: the if statement is not in the while loop. This is probably causing your incorrect result, though the right set of inputs should give a nonzero result.

putting all that together looks like

do
{
cout << "Enter a number: ";
cin >> num;
if(num%2 && num != -1) //just in case, lets not add -1, which I think is considered "odd" by the logic
sum+= num;
}
while (num != -1)


count is not used.
Last edited on
Thank you for a well formed, clear first post!

The first problem is that lines 17-20 execute outside the loop. You need to move them inside the loop.

The second problem is that line 19 defines a new local variable called SUM, adds its uninitialized value to num, and then throws the result away. You should define sum at the top of main, like you define count and num. Be sure to initialize it to zero.
^^^ good catch.. I took the int off sum instinctively but didnt catch that issue in the original.
Topic archived. No new replies allowed.