prompting until given a postive odd integer

int x;
cout << endl;
while ( (x%2 == 0)||(x<=0) ) {
cout << "Enter an odd positive integer: "; // if x is >0 prompt
cin >> x;
}
cout << endl;


hi I need to write a c++ program that prompts the user to enter a postive odd integer and keeps prompting until they have done so.
I thought of using the while instruction to repeat but that only gives me even numbers so I tried this angle but it didn't work. Any ideas ??

Comments

  • First, I notice you are allocating space for the variable x, but you do not assign x a value. And then you have the statement

    [code]
    while ( (x%2 == 0)||(x<=0) )
    [/code]

    Perhaps you should move this statement down to a point [italic]after[/italic] x has been assigned a value.

    You might also do a quick check right after input that the value actually is an integer rather than a letter or something else (try to catch errors in the input data).

  • [code]: int x[color=Red]=0[/color];
    : cout << endl;
    : while ( (x%2 == 0)||(x<=0) ) {
    : cout << "Enter an odd positive integer: "; // if x is >0 prompt
    : cin >> x;
    : }
    : cout << endl;
    [/code]
  • You *might* try the do-while loop instead.

    [code]#include
    #include

    using namespace std;

    int main(void) {

    int x;

    do {

    cout << "enter an odd positive integer: ";
    cin >> x;

    assert(cin.good()); // loopy alert

    } while(x % 2 == 0 || x < 0);

    cout << "you entered: " << x << endl;

    return (0);
    }[/code]

    As mentioned, you may also want to use a char[] or string to read in the number and then use a conversion function in case someone enters invalid input.

    HTH
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories