Q:

C++ Program to check if a number is even using Recursion

0

C++ Program to check if a number is even using Recursion

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to check leap year... >>
<< C++ Program to find odd or even number without usi...