This if-else statement prints whether an integer number n is odd or even. A number is even if it is divisible by 2. Thus, if expression n % 2 == 0 is true, number n is even; otherwise it is odd. Alternatively, we can write this if statement as follows:
if (n % 2 == 1)
printf ("odd");
else printf("even");
Note that as the arithmetic expression n % 2 evaluates as 1 (i. e., true) when n is odd and 0 (i. e., false); otherwise, the equality test in this if-else statement is not required. Thus, we can write the test expression in simply as n % 2. However, such statements are somewhat difficult to understand and should be avoided, particularly by beginners.
#include<iostream.h>
#include<conio.h>
void main()
{
int n ;
clrscr( ) ;
cout<<"Enter any number : ";
cin>>n ;
if (n%2 == 0)
{
cout<<"The number is even"<<endl ;
}
else
{
cout<<"The number is odd" ;
}
cout<<"Press any Key to Exit.";
getch() ;
}
Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.
Related Articles
Basic Courses
Advance Courses