C program to find the maximum between three numbers using ternary operator

C program to find the maximum between three numbers using ternary operator

In this C program we find the maximum between three numbers using a ternary operator.For eg 8,4,10 the maximum of these numbers is 10.So 10 should be are output.

Ternary operator :- condition?true:false

For eg  a<b?printf(a):printf(b)

Logic

Ternary Operator is used in the following way condition?true:false.

Dry Run of the Program

Let us say a=10 , b=18,c=12

Use of 1st ternary operator

a(10)>b(18)?a(10):b(18) means if a>b is true then store the value of a in another variable t.But in this case ‘a’ is not greater than ‘b’ so we store the value of ‘b'(18) in t.So now t=18.

Use of 2nd ternary operator

t(18)>c(12)?t(18):c(12) means if t > c is true then we store the value of t in another variable max.In this case it it is true t(18)>c(12), so we store the value of t in the variable max.Now we have the value of max=18.Print the output.

Program

#include<stdio.h>
void main()
{
    int a,b,c,t,max;
    printf("enter 3 numbers\n");
    scanf("%d%d%d",&a,&b,&c);
    t=a>b?a:b;
    max=t>c?t:c;
    printf("\nmax value is %d",max);
}

Output

Share Me!