# Odd and even

Printable View

• 09-18-2006
swgh
Odd and even
I am attempting to create a little sub program that reads a number rrom
the user then prints if it is odd or even. This is what I have come up with, but it keeps printing the number is odd. Is there anything I can do to change this?

Code:

```int main ( void ) {   int n;             cout << "Enter a number: ";   cin >> n;             if (( n % n ) / 2 )       cout << "\nThe number is even" << endl;               cout << "\nThe number is odd" << endl;               cin.get();  // freeze console window     cin.ignore();         return 0;  // indicate program ended sucsessfully }```
• 09-18-2006
itsme86
Code:

`if (( n % n ) / 2 )`
Work that out in your head. A number divided by itself is always 1 with no remainder. Try just n % 2.
• 09-18-2006
swgh
Lol. sorry, its ok I just solved it.

My if statement was almost right, I changed it to

Code:

`if (( n / 2 ) % n )`
and it works ok now. Thanks isme86 for the reply, I need my brain exchanged for a new one!
• 09-18-2006
Daved
>> if (( n / 2 ) % n )
That formula is incorrect, are you sure it works ok now? Why not use n % 2? Also, you are missing an else in your code.
• 09-18-2006
indigo0086
The correct code is. Your code isn't working like you think it should, it isn't comparing two values, just evaluating a statment and feeding it into an if statement.
Code:

`if((n % 2) == 0)`
that means if a number n divided by 2 has a remainder of zero, it is even. Otherwise it is odd.
• 09-18-2006
swgh
Thanks guys. I really should learn to think formula's through before I rush ahead and input them. Great advise, I'l remember your tips for next time too.
• 09-18-2006
Salem
• 09-18-2006
bumfluff
Apart from the slight problem of the lack of else statement.
• 09-18-2006
swoopy
Quote:

Originally Posted by Salem

Not only remarkable, but also wrong.
• 09-18-2006
Salem
LOL - so it is.
• 09-18-2006
major_small
yeah... somebody needs to fix that... and make a C++ version... introducing C code to somebody trying to learn C++ can send confusing and mixed messages... even though the algorithm is the same.
• 09-18-2006
bumfluff
There should be a fully C++ FAQ and a Fully C FAQ.
• 09-18-2006
Dave_Sinkula
Quote:

Originally Posted by major_small
yeah... somebody needs to fix that...

Yeah, that's been the state of it for a while.
http://cboard.cprogramming.com/showthread.php?t=82195