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
#include <iostream>
usingnamespace 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;
}
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)
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.