Select Page

# C++ Program to Check Whether Number is Even or Odd (Using Ternary operator)

by | Jan 8, 2023 | C++, C++ Programs

## Introduction

This program will make use of the Ternary operator to check whether a number entered by the user is even or odd.

An even number is one that is exactly divisible by 2. On the other hand, an odd number is one that is not exactly divisible by 2.

To write this program, you should know about the following C programming concepts:

• Operators (Ternary operator)
• The ternary operator is represented as
(condition)? statement1: statement2

## Program

```#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter an integer: ";
cin>>n;

(n%2==0)?cout<<n<<" is a even number.":cout<<n<<" is a odd number";
// ternary operator
return 0;
}```

## Explanation

‘n’ is an ‘int’ type variable. The value entered by the user gets stored in it.

(n%2==0)? cout<<n<<” is an even number.”: cout<<n<<” is a odd number”;

The above statement is written using the Ternary operator.

n%2==0 is the condition part of the ternary operator followed by ?.

cout<<n<<” is a even number.” and cout<<n<<” is a odd number”; are the statement1 and statement2 respectively of the Ternary operator separated by ‘:

If the condition is true, then the statement1 is executed otherwise statement2 gets executed.

Since (99%2==0) is not true thus, statement 2 gets printed on the screen.