## Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of posts: 16943

This Forum Only

prompting until given a postive odd integer Posted by batman101 on 12 Oct 2009 at 6:35 AM
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 ??
Re: prompting until given a postive odd integer Posted by David_B on 12 Oct 2009 at 10:05 AM
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

```while ( (x%2 == 0)||(x<=0) )
```

Perhaps you should move this statement down to a point after 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).

Re: prompting until given a postive odd integer Posted by AsmGuru62 on 13 Oct 2009 at 1:21 AM
```: int x=0;
: cout << endl;
: while ( (x%2 == 0)||(x<=0) ) {
: cout << "Enter an odd positive integer: ";  // if x is >0 prompt
: cin >> x;
: }
: cout << endl;
```
Re: prompting until given a postive odd integer Posted by pseudocoder on 13 Oct 2009 at 1:53 AM
You *might* try the do-while loop instead.

```#include <iostream>
#include <cassert>

using namespace std;

int main(void) {

int x;

do {

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

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

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

return (0);
}```

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

## Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic