The Conditional Operator

Default Image

onditional operator is somehow substitute
to the if-else structure. It is also used to make two-way decision as
we made in if-else. We need three operands to complete conditional
operator statement that’s why it called ternary operator. It is denoted
by question mark (?) and colon (:). General syntax for conditional
operator is:

(condition)? statement1: statement2;


In above syntax condition is the logical
or relational expression, statement 1 will execute if condition is true
and statement 2 ignored as ignored in if-else structure. If condition is
false, then statement 1 will be ignored and statement 2 will be
executed. Let’s convert if-else example in conditional operator.

#include

#include

void main()

{

int a;

clrscr();

cout<>a;

(a>50)?cout<<"Number is greater than 50\n" :cout<<"Number is smaller than 50\n";

cout<50)?"Number is greater than 50\n" :"Number is smaller than 50\n";

getch();

}


As you observe in above example conditional operator statement is
written in two different types. 1st line will show the whole statement
and 2nd statement will show only true as 1 and false as 0.








Enter a number :45


Number is smaller than 50


0








Enter a number :75


Number is greater than 50


1


conditional opeator output


You can get source code from here

Read Count: 3 times

Comments

No comments yet.

Leave a Comment