C++ program to print odd and even numbers
In this chapter of C++ program tutorial out task is to:
-
Write a C++ program to find if a number is even or odd.
C++ program to find a number is even or odd
METHOD 1:
Below is the C++ program to find a number is even or odd
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number:"<<endl;
cin>>n;
if(n%2==0) // or we can use (n%2!=1)
{
cout<<"The number is EVEN."<<endl;
}
else
{
cout<<"The number is ODD."<<endl;
}
return 0;
}
OUTPUT :
Enter the number:
5
The number is ODD.
EXPLANATION :
In the above program:
-
The execution starts from the main function (here int main()).
-
A 4 bit memory space is created for the integer 'n' (assuming 64 bit system).
-
Then the number is taking as the input.
-
The condition for "Even" or "Odd" is executed through the if statement.
-
Then the number is diplayed as "Even" or "Odd".
-
The program than gives the desired output and terminates in the line "return 0" returning a 0 value.
WORKING :
a = 5
if(5%2==0) // This returns a false value so it will move to the else statement and execute the statement
You can see the above code execution and output in codeblocks IDE:
METHOD 2: (using bitwise AND)
Below is the C++ program to find a number is even or odd
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number:"<<endl;
cin>>n;
if(n&1)
{
cout<<"The number is ODD."<<endl;
}
else
{
cout<<"The number is EVEN."<<endl;
}
return 0;
}
OUTPUT :
Enter the number:
5
The number is ODD.
EXPLANATION :
In the above program:
-
The execution starts from the main function (here int main()).
-
A 4 bit memory space is created for the integer 'n' (assuming 64 bit system).
-
Then the number is taking as the input.
-
The condition for "Even" or "Odd" is executed through the if statement.
-
Then the number is diplayed as "Even" or "Odd".
-
The program than gives the desired output and terminates in the line "return 0" returning a 0 value.
WORKING :
a = 5
if(a&1) // 0101 & 1 = 0100 [4]
So when it is a odd number it get decremented by 1 and we have to print it odd and for even number it get incremented by 1 and we have to print it even.
You can see the above code execution and output in codeblocks IDE:
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Sayantan Bose
- š Iām currently working on DS Algo skills
- š± Iām currently learning web develeopement
- šÆ Iām looking to collaborate with Oppia
- š« Reach me at https://www.linkedin.com/in/sayantan-bose-14134a1a6/
- š Pronouns: his/him
Page Views :
Published Date :
Sep 13,2020