Ternary operator or Conditional operator (?:)

Ternary Operator is a special operator defined in 'C' language.  It is also known as conditional operator and single line comparison operator. Ternary operator is used in place of if else statement. it is denoted by (? :) and first of all condition will be checked if it is true then statement of ? will be executed and if it is false then statement of : will be executed.

टर्नरी ऑपरेटर- यह सी लैंग्वेज में उपलब्ध एक विशेष ऑपरेटर है, इसे कंडीशनल ऑपरेटर एवं सिंगल लाइन कम्पेरीशन ऑपरेटर के नाम से भी जाना जाता है। इसका प्रयोग if...else के स्थान पर किया जाता है। इसे (? :) से दर्शाया जाता है एवं यहाँ सर्वप्रथम कंडीशन चेक की जाती है यदि यह सत्य है तब ? के स्टेटमेंट रन होते है अन्यथा कंडीशन के असत्य होने पर : के स्टेटमेंट रन होते है।  

Syntax:-
(condition)? statement (true) : statement (false);     

Example :- 
int x=10,y=20;
(x<y)? printf("%d is greater\n",y): printf ("%d is a greater \n",x);
Example:-
1.)Cpp program to find that given number is even or odd using ternary operator ?:
#include<iostream.h>
#include<conio.h>
void main(){
int num;
clrscr();
cout<<"Enter number = ";
cin>>num;
(num%2==0) ?cout<<num<<" is Even Number"<<endl :cout<<num<<" is Odd Number"<<endl;
getch();
}

2.) C++ program to find greatest/largest of three numbers using ternary operator ?:
#include<iostream.h>
#include<conio.h>
void main(){
float a,b,c;
clrscr();
cout<<"Enter Three Numbers"<<endl;
cin>>a>>b>>c;
(a>b)?(a>c)?cout<<a<<" is greatest"<<endl:cout<<c<<" is greatest"<<endl:(b>c)?cout<<b<<"is greatest":cout<<c<<"is greatest";
getch();
}

No comments:

Post a Comment