954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ How to allow only odd numbers to be inputted

I'm trying to create a piece of C++ code which will only allow a user to enter odd numbers.
If an even number is entered, the program must tell the user to enter only an odd number.

Im comfortable with the whole output bit in the 2nd line above, but i have no idea where to start with regards to analysing the number!

Any help would be greatfully received!!

nathanrt
Newbie Poster
1 post since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

welcome aboard....please post what you've got so that w can guide you. Here is some pointers:
1. start with your headers, you'll need to figure out which ones you'll need:

#include<iostream>

2. You need:

using namespace std; 

int main()

3. you need to declare some variables:

int num;

4. Ask the user to input a number:

cout << "Enter an integer: ";

5.Allow the user to input:

cin >> num;

6. For the actual calculation, we use the modulos (%) operator. From basic math/algebra, you ought to know theoretically, how to calculate even and odd numbers....do they have remainders....if they do...what's the remainder.
7.

if (expression)
	statement1
else
	statement2

The above test to see if the number is odd or not...if it is, do something...if it's not....do something.
8. Then you'll need output statements (answers to provide) to you professor:

cout << num << " is an odd number" << endl;

In the future....search the internet(GOOGLE)...or the frum to see if the problem has been covered already.
10. most importantly...to be successful in c++ you'll simply have to do the work....and practice...
Hope this helps...have a good day!

zandiago
Nearly a Posting Maven
2,480 posts since Jun 2007
Reputation Points: 129
Solved Threads: 26
 

If a number is divisible by 2, it's even. If it's not divisible by 2, it's odd. You can find out if a number is divisible by 2 by finding the remainder of division by 2. C++ has a remainder operator, %. So it stands to reason that if you have a number x, you can say:

if ( x % 2 != 0 ) {
  // The number is odd
}

Ne?

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You