Ternary ? :

Similar to the if statement, tests if a condition is true or false.

 

aka 'conditional operator' or the 'arithmetic if' operator.

 

Syntax:

condition ? true : false ;

 

Line 14, assigns the result of the ternary test condition to the uninitialised variable max:

#include <iostream>
using namespace std ;

int main () {

	int a, b, max;

	cout << "Please enter the 1st number:" << endl ;
	cin >> a ;

	cout << "Please enter the 2nd number:" << endl ;
	cin >> b ;

	max = (a > b) ? a : b ;

	cout << "The larger number was: " << max << endl ;

	return 0;
}

Compile & Run:

Please enter the 1st number:
5637
Please enter the 2nd number:
12
The larger number was: 5637

 

Leave a Reply