C++ Program To Check Number Is Even Or Odd Using If/Else Statements
In this tutorial, we will that how we can find if any number is even or not with the help of if-else statements.
Program To Check Number Is Even Or Odd Using If/Else Statements In C++
Example 1: If entered number is an even number.
Let value of 'a' entered is 8
if(a%2==0) then a is an even number, else odd.
i.e. if(8%2==0) then 8 is an even number, else odd.
To check whether 8 is even or odd, we need to calculate (8%2).
/* % (modulus) implies remainder value. */
/* Therefore if the remainder obtained when 8 is divided by 2 is 0, then 8 is even. */
8%2==0 is true
Thus 8 is an even number.
Example 2: If entered number is an odd number.
Let value of 'a' entered is 7
if(a%2==0) then a is an even number, else odd.
i.e. if(7%2==0) then 4 is an even number, else odd.
To check whether 7 is even or odd, we need to calculate (7%2).
7%2==0 is false /* 7%2==1 condition fails and else part is executed */
Thus 7 is an odd number.
#include<bits/stdc++.h>
using namespace std;
void check_number(int num){
if(num%2==0){
cout<<num<<" is an even number";
}
else{
cout<<num<<" is an odd number";
}
}
int main(){
int num;
cout<<"Enter the number you want to check:-";
cin>>num;
check_number(num);
return 0;
}
Enter the number you want to check:-
8
8 is an even number
Conclusion
Here, we have how to implement the C++ code for checking whether the number given by the user is an even or an odd number.