A Learning Platform

SUCCESS

Success = Discipline + Consistency + Sacrifice.
Discipline - in what you do.
Consistency - in what you do.
Sacrifice - for what you do.

                   -- Manjunatha C. P. --

C Program: Biggest of Three numbers using Conditional operator

The easiest way to find the biggest of 3 numbers is using Conditional operator. The program code is very short compared to other methods.

The conditional operator is a decision-making statement.
It is also called as a ternary operator because it operates on three operands.
It is represented by two symbols, i.e., ‘?'(question mark) and ‘:'(colon).

Description:

Program takes any 3 numbers and prints the greatest number using conditional operator.
a, b and c are three input integer or float or double numbers.
Since the conditional operator is taking 3 operands a, b and c, it is called as ternary operator.

Algorithm to calculate biggest of 3 numbers using ternary operator:

STEP 1: START
STEP 2: READ any three numbers
              READ a, b, c
STEP 3: COMPARE a, b and c using Conditional operator
               ( a > b and a >c )?
                             big = a
              OTHERWISE ( b > c )
                             big = b
              else
                             big = c
STEP 4: PRINT the biggest number
              PRINT big           
STEP 5: END

Program to find biggest of three numbers using conditional operator:

#include<stdio.h>  
#include<conio.h>
int main()  
{  
    float a, b, c, big;  
    printf("\nEnter any 3 numbers: ");  
    scanf("%f%f%f", &a, &b, &c);  
    big = (a>b && a>c) ? (a) : ( (b>c)?(b):(c) );  
    printf("Biggest number is: %f ", big);  
    getch();
    return 0;  
}  

Output 1:

Enter any 3 numbers: 1.4 -5 0
Biggest number is: 1.400000

Output 2:

Enter any 3 numbers: -44 -2 -12
Biggest number is: -2.000000

Additional information:

Syntax:
(Expression1)? (expression2): (expression3);

The expression1 is a Boolean condition that can be either true or false.
If the expression1 evaluates to true, then the expression2 will be executed.
And the result of expression2 will be the result of whole expression.
If the expression1 evaluates to false, then the expression3 will be executed.
And the result of expression3 will be the result of whole expression.

Examples:

vote = ( age >= 18 )? 1 : 0;
a=2;
b=5;
big = (a>b)? a : b;