Program to calculate the greatest of three numbers using conditional operator in C/C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code
  4. Download Code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


In the above program the nested conditional operator is used to compare three numbers. First it checks whether (a>b) and if it is TRUE then it checks whether (a>c) and i it is TRUE then the value of variable ‘a’ is assigned to variable ‘d’ otherwise value of variable ‘c’ is assigned to variable ‘d’. Similarly we can for other also.

Output:
Enter three numbers a,b,c:
11 25 15
Greatest number =25

Important information for beginners:

1. Conditional operator (?:) is the only ternary operator available in C++ which operates on three operands.

2. The conditional operator together with operands from a conditional expression which the takes the following form
expression1?expression2:expression3

Here ‘expression1′ is a test condition which is evaluated first. If it is true then ‘expression2′ is evaluated and this becomes the value of the conditional expression. However if it is false then ‘expression3′ is evaluated and this becomes the value of the conditional expression. The value of the conditional expression can also be assigned to another variable.

3. The conditional operator is short hand version of the if-else statement which can be represented as:

if(a>b)
c=a;
else
c=b;
4. The conditional operator has a higher precedence than the assignment operator.