×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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 [Last updated : February 27, 2023]

Checking if a number is EVEN using Recursion

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.

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

#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);

    return 0;
}

Output

First run:
Enter a number: 101 
Is is an ODD Number 

Second run:
Enter a number: 120 
It is an EVEN Number 

Solution Explanation

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.

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.