For checking ether the given number is odd or even we commonly use the method of dividing the given number by 2. If the given number is evenly divisible by 2 with a reminder of 0, then the number is even. And if the number leaves a remainder of 1, then the given number is odd. For doing the division and getting the remainder, we use the modulus operator '%'
The modulo operator, denoted by %, is an arithmetic operator which produces the remainder of an integer division.
We can calculate the reminder with the modulo operator % like this num % 2 = = 0
Call the main function to start the program execution. Within the main body declare an integer type variable n. Ask the user to enter a number. Read this number to the variable n by using the object cin
. Now check whether the remainder of n divided by 2 is 1 or 0. To find the reminder the arithmetic operator % is used. This can be used like n % 2 = = answer.
Now you have to check if it is 0 or 1. For this simple, if…..else
statement is used.
In C++ the if….else
statement is used to run one block of code under certain conditions and another block of code under different conditions.
if (condition)
{
……….
} else
{
……….
}
Here we check whether (n % 2 = =0 )
is true or not. If the expression is true, n is even. Display a message the number is even.Else n is odd. Display a message the number is odd.
Let's take some simple examples to understand more about this.
Let the entered value be 'n = 7'. According to the logic, we used in the C program, if '(n%2 = 0)', then a is an Even number otherwise Odd. Here 'n = 7', then we have (7%2 not equal to zero), so the given number is Odd
Let entered value 'n = 10'. In accordance with the program logic, if (n%2 == 0), then a is an Even number otherwise Odd. Here 'n = 10',then we have (10%2 = 0),so the given number is Even.
Step 1: Call the header file iostream.
Step 2: Use the namespace std.
Step 3: Open the main function as integer, int main().
Step 4: Declare an integer type variable n.
Step 5: Print a message “Enter an integer”.
Step 6: Read the value to the variable n.
Step 7: Check the reminder, if ( n% 2 = = 0) then Print n is even. else, print n is odd.
Step 8 : Exit.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a Number ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Run 1 --------------------- Enter a Number: 10 10 is even. Run2 --------------------- Enter a Number: 14 14 is even.