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.
Program to check EVEN or ODD using Recursion in C++
Output
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.
need an explanation for this answer? contact us directly to get an explanation for this answer