So technically I have done what the assignment says because this works:
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int sum = 0;
cout << "Please enter an odd positive integer: " << endl;
cout << "This program will end if number is <= 0 or decimal" << endl;
cin >> number;
while (number > 0)
{
if (number % 2 != 0)
sum = sum + number;
else
cout << "That number was even - please enter odd number \n";
cin >> number;
}
cout << "Sum of odd numbers = " << sum << endl;
return 0;
}
However - it dawned on me that the program quits when someone enters a double or enters a character, rather than just warning that this will happen - I would love to write this in. I have tried using else if statements and I am not getting the desired results. I am not asking for someone to solve this for me per se but if I could just get sent in the right direction. We are currently working on while and for loops and increments (which don't seem to apply here at all)
First off, you'd have to change your number
variable to a string
to take in "anything", deal with garbage input, and finally convert it to an int
if it fit your requirements. This usually isn't too hard, but can get tricky at times. Google is usually your friend here. It's bee a while since I did C++, so I'd have to consult it, too, to get things correct.
And when you say "double", is that the number is 2 digits or is too long to be an int
? That little bit of ambiguity is throwing me off. If it's just too big a number being an actual double
datatype, the string
should help with that, as would a problem a 2 digit number.
And for an increment being useful, you could use sum += number;
, depending on your version of C++. Older versions don't allow that, but newer versions do. I'd be surprised of a gcc or other compiler wasn't new enough to have it available, at this point.