C++ Conditional operator statement

The conditional operator statement is used with the combination of ? and : and this is known as conditional operator.

Syntax:                         conditional expression ? expression1 : expression2

The conditional expression is evaluated first and if the result is nonzero then the expression1 is returned as the value of the expression, otherwise the value of expression2 is returned.

For example:

If(a<1)

t=0;

else

t=1;

Here the above code can be written as:

t = (a<1) ? 0:1;

Program:

/*PROGRAM TO FIND LARGEST NUMBER B/W THREE NUMBERS USING CONDITIONAL OPERATOR*/

#include<conio.h>

#include<iostream.h>

class largest

{

int a,b,c;

public:

void input();

void output();

};

void largest::input()

{

cout<<“Enter any three numbers: “;

cin>>a>>b>>c;

}

void largest::output()

{

(a>b && a>c)?cout<<a<<” is greatest”:((b>c &&

b>a)?cout<<b<<” is greatest”:cout<<c<<” is greatest”);

}

void main()

{

largest l1;

clrscr();

l1.input();

l1.output();

getch();

}

Leave a Reply

Your email address will not be published. Required fields are marked *