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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.