Signup/Sign In

C++ Check whether the given Number is Even or Odd

Hello Everyone!

In this tutorial, we will learn how to Check whether given number is Even or Odd, in the C++ programming language.

Code:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to find the given number is Even or Odd ===== \n\n";

    //variable declaration
    int n;

    //taking input from the command line (user)
    cout << " Enter the number that you want to check : ";
    cin >> n;

    //logic to check if the number is even or odd
    if(n % 2 == 0)
    {
        cout << "\n\nThe entered number "<< n << " is Even\n";
    }
    else
    {
        cout << "\n\nThe entered number "<< n << " is Odd\n";
    }

    cout << "\n\n\n";

    return 0;
}

Output:

C++ even or odd

Now let's see what we have done in the above program.

Program Explained:

Let's break down the parts of the code for better understanding.

if(n % 2 == 0)
{
    cout << "\n\nThe entered number "<< n << " is Even\n";
}
else
{
    cout << "\n\nThe entered number "<< n << " is Odd\n";
}

The code snippet represents the logic to determing whether the given number is even or odd.

There are many ways to achieve this, but here we wanted to introduce the logic of conditional statements if else as well as the use of the modulus operation (%).

if(condition):

This part of the code is executed when the condition is true. If the condition is false, then the code will ignore this part of the code and move to the next line following this.

n%2: Here the modulus operation returns the remainder obtained when n is divided by 2.

By definition of an even number, the remainder obtained on dividing a number by 2 has to be 0. For Odd, the remainder has to be 1.

Keep Learning :)



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.