C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Wednesday, March 21, 2018

Write a C++ Program To Check a Number For Even Odd Using Conditional Operator Ternary Operator

Here is the C++ source code  for the program that will input an integer number and will
check this number whether it is even or odd. But this program will not use if else statement for checking this number for even / odd. Rather it will use C++ Conditional operator / Ternary operator for this purpose as shown in the following figure of the even odd program using ternary operator:

Easyway C++ Program to check a number for even odd using conditional operator or ternary operator
Easyway C++ Program to check a number for even odd using conditional operator or ternary operator
Here is the C++ program:

#include<iostream.h>
#include<conio.h>
void main()
{
    int n;
   clrscr();
    cout<<"Enter a number to check for Even / Odd = ";
    cin>>n;
    (n%2==0) ? cout<<"Number is Even" : cout<<"Number is odd";
    getch();
}


A sample execution of the program even odd with conditional operator is as follows:

when user enters 10 the output will be Number is Even
and when user enters 111 then output message shown will be Number is Odd.


Program C++ To Check number even or odd with ternary operator / conditional operator output
Program C++ To Check number even or odd with ternary operator / conditional operator output

Explanation of Logic behind : Even / Odd Program i C++ with Ternary Operator or Conditional Operator

The main statement of this program is using Conditional operator. 

The conditional operator has the syntax:

(condition)? case_if_true : case_if_false ;

Working of Conditional Operator

The condition will be checked first of all, if condition is true then first statement is executed otherwise second statement is executed, as shown in the following line of code.

Note: here in true_case and false_case we can use only:
 arithematic expression, constant value, input / output statement;
}

(n%2==0) ? cout<<"Number is Even" : cout<<"Number is odd";

so if we enter 10

condition becomes 10%2==0  

We know that % gives remainder so 10%2 will give zero

so condition becomes 0 == 0 which is true 

so first statement is executed and output message is displayed: Number is Even.




Share:

0 comments:

Post a Comment

We Love To Hear From You!

EasyCPPprogramming.blogspotcom

Labels