Sunday, August 2, 2009

Write a c++ code to check wether a given number is odd or even?

AND the number with 0x1, if its true then its odd, if false, then even.

Write a c++ code to check wether a given number is odd or even?
Program that check whether a given number is odd or even:





#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;stdio.h%26gt;


void main()


{


int i;


clrscr();


cout%26lt;%26lt;"Enter a Number :";


cin%26gt;%26gt;i;


if((i/2)==0)


{


cout%26lt;%26lt;"Its a even number";


}


else


{


cout%26lt;%26lt;"its a odd number";


}


getch();


}
Reply:The key is the modulo operator (%).





The following code will do:





#include %26lt;iostream%26gt;


using namespace std;


int main() {


int x;


cin %26gt;%26gt; x;


if(x%2) {


cout %26lt;%26lt; x %26lt;%26lt; " is odd";


} else {


cout %26lt;%26lt; x %26lt;%26lt; " is even";


}


return 0;


}
Reply:Using bitwise AND (%26amp;) is MUCH faster than division or modulus.





#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;stdio.h%26gt;


void main()


{


int i;


clrscr();


cout%26lt;%26lt;"Enter a Number :";


cin%26gt;%26gt;i;


cout %26lt;%26lt; i %26lt;%26lt; " is an " %26lt;%26lt; (i%26amp;1) ? "odd" : "even" %26lt;%26lt; " number."


getch();


}
Reply:Check and see if the modulus of being divided by two is one or zero. If it is one it is odd, if it is zero it is even.
Reply:The above posters who mention bitwise AND have the most efficient/correct answer. Here's the corrected version for above poster's program.





#include %26lt;iostream%26gt;


using namespace std;





int main()


{


int i = 0;


cout %26lt;%26lt; "Enter a number: ";


cin %26gt;%26gt; i;


cout %26lt;%26lt; i %26lt;%26lt; " is an " %26lt;%26lt; (i%26amp;1) ? "odd" : "even" %26lt;%26lt; " number." %26lt;%26lt; endl;


return 0;


}





C++ has been revised in 99, hence the iostream, not iostream.h. All the standard functions are in the standard namespace. Hence using namespace std;. Main returns an int, so it's int main, not void main. Drop the conio.h, it's non-standard.

hyacinth

No comments:

Post a Comment