Home »
C++ programs »
C++ Most popular & searched programs
C++ Program to check if a number is even using Recursion
This program will read a number and check whether it is EVEN or ODD using recursion in C++.
Submitted by Abhishek Pathak, on April 09, 2017
There are various techniques of finding whether a number is even or not, the popular one being through the modulus operator. However, there is another method of finding it with the help of recursion.
Program to check EVEN or ODD using Recursion in C++
#include <iostream>
using namespace std;
//function prototype/declaration
int isEven(int);
int main()
{
int n;
cout<<"Enter a number: ";
cin>>n;
if(isEven(n))
cout<<"It is an EVEN Number";
else
cout<<"Is is an ODD Number";
cout<<endl;
return 0;
}
//function definition/body
int isEven(int n)
{
if(n == 0)
return 1;
else if(n == 1)
return 0;
else if(n<0)
return isEven(-n);
else
return isEven(n-2);
}
Output
First run:
Enter a number: 101
Is is an ODD Number
Second run:
Enter a number: 120
It is an EVEN Number
In this program we are using the function recursion technique. We are recurring function until the value of n is either 1 or 0. If it ends at one of these values, the function returns 1 for even number and 0 for not even.
We have called the function inside of if statement. When the number is true, the function returns 1 and the result of if expression is true and similar is the case of non-even number.
TOP Interview Coding Problems/Challenges