Tuesday, July 28, 2009

C++ Small Program which validates a number as odd or even?

How can i write a C++ program that lets a user enter a number, this number must be odd %26amp; between say 5 %26amp; 50.





The program validates the number by checking if its between 5 %26amp; 50 and then validates it being an odd number.





If it the user enters a number outside of these brackets and or enters an even number it will give them the option to try again?





Many thanks in advance

C++ Small Program which validates a number as odd or even?
int num = 3;





if( ! ( num % 2 ) )


cout %26lt;%26lt; "this number is even!" ;


else


cout %26lt;%26lt; "this number is odd!" ;








//cin is used to get user input.


cout %26lt;%26lt; "please enter a number:" ;


cin %26gt;%26gt; num;








//conditional statements are used to validate range


if(num %26gt;5 %26amp;%26amp; num %26lt;50)


{


// [ this code seg will execute for numbers between 5 %26amp; 50]


}


else


{


cout %26lt;%26lt; "bad number - out of range!";


}








///sorry i didn't leave very much for you to do. but, there are some things left to do!
Reply:Use modulus operator, %.





if(number % 2 == 0) =%26gt; number is even


else number is odd.


No comments:

Post a Comment