C++ Program to Check Whether Number is Even or Odd

144
views
Check Even or Odd
(Last Updated On: September 1, 2018)

In this example, the if…else statement is used to check even or odd and whether a number entered by the user is even or odd.

 To understand Check Even or Odd program, you should have the knowledge of following C++ programming topics:
  • C++ if, if…else and Nested if…else

Integers which are perfectly divisible by 2 are called even numbers.

And those integers which are not perfectly divisible by 2 are not known as an odd number.

To check whether an integer is even or odd, the remainder is calculated when it is divided by 2 using modulus operator %. If the remainder is zero, that integer is even if not that integer is odd.

Program to Check Whether Number is Even or Odd using if else

#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter an integer: ";
    cin >> n;

    if ( n % 2 == 0)
        cout << n << " is even.";
    else
        cout << n << " is odd.";

    return 0;
}

Output

Enter an integer: 23
23 is odd.

In this program, the if..else statement is used to check whether n%2 == 0 is true or not. If this expression is true, n is even if not n is odd.

You can also use ternary operators ?: instead of the if..else statement. The ternary operator is shorthand notation for if…else statement.

[irp]

Program to Check Whether Number is Even or Odd using ternary operators

#include<iostream>

using namespace std;

int main()
{
	int a;

	cout<<"Enter the Number : ";
        cin>>a;

	(a%2==0)?cout<<"Number is even":cout<<"Number is odd";
	
	return 0;
}

Output

Enter the Number: 56
Number is even

[irp]

Here are few Related CPP Program

Ask your questions and clarify your/others doubts on how to Check Even or Odd in C++ by commenting. Documentation