Simple Conditional or Ternary Operators Example Program In C++
On this page (8sections)
About this program
This is an example program in c operator example programs. Read the concept first: Arithmetic Operators Example in C++, then study the code and output below.
Definition
Check condition if true, it returns first variables value otherwise return second values. sometimes it replaces if..else statement
Syntax
Condition? Expression1: Expression2
Example
(a>10) ? b : c
Explanation For Conditional or Ternary operator
Given that
a, b, c
are expressions;
the expression
(a>10) ? b : c
has as its value b if a is nonzero, and c otherwise. Only expression b or c is evaluated.
Expressions b and c must be of the same data type. If they are not but are both arithmetic data types, the usual arithmetic conversions are applied to make their types the same. It is also called ternary operators.
Example Program For Conditional or Ternary operator
// Header Files
#include<iostream>
#include<conio.h>
//Main Function
using namespace std;
int main ()
{
// Variable Declaration
int a = 10;
int b = 15;
int c;
cout << "Simple Conditional or Ternary Operators Example Program \n";
c = a <= b ? a : b; //Conditional or Ternary
cout<<"\nC Is "<<c;
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
Sample Output
Simple Conditional or Ternary Operators Example Program
C Is 10
Related Pages
Learn the concept first, then study the code:
- C++ Programs — Browse all C++ Programs.
- Arithmetic Operators Example in C++ — Tutorial — arithmetic, relational and logical operators.
- Simple Relational Operator Example Program In C++ — More in c operator example programs.
- Simple Logical Operators Example Program In C++ — More in c operator example programs.