How to use ternary operator in c language

program to use ternary operator in c language


#include<stdio.h>
int main()
{
    int y,z,max;
    printf("Enter values for y and z : ");
    scanf("%d%d",&y,&z);
    max = z>y ? y : z;
    printf("larger of %d and %d is %d\n",y,z,max);
    return 0;
}

output


Enter a values for y and z : 12
4
larger of 12 and 4 is 12

Steps Description

  1. Declare integer three variable y , z and max
  2. printf inbuild function to display value of variable y and z with respective decimal placeholder %d
  3. Evaluation of variable y and z to determine greater than z
  4. Assign max variable with greater than variable y
  5. printf inbuild function to display larger value of variable y

Ternary Operator in JavaScript Language

Program to use Ternary Operator JavaScript Language


let a = 10;
let b = 20;
let max;
max = a > b ? a : b;
console.log("Max Number is =", max);

Output


Max Number is = 20

Steps Description

  1. Declare three variables a, b and max
  2. Initialize three variables with value of 10, 20 respectively a=10, b=20 and max
  3. Ternary operator works like if else
  4. condition is checked first value is true expression1 displayed condition is false expression2 displayed
  5. console.log inbuild function to display max variable number