Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find greatest among two numbers using ternary operator

C Code Example — Basic Programs

ADVERTISEMENT

C Program to find greatest among two numbers using ternary operator

Objective

Write a C program to find the greatest of two numbers using the ternary operator.

Algorithm / Approach

  1. Declare variables a and b.
  2. Read a and b.
  3. Use the ternary operator directly inside a statement: (a > b) ? printf("A is Greatest") : printf("B is Greatest");.
main.c
#include<stdio.h>
int main( ) {
 int a, b;
 printf("Enter Values for A : ");
 scanf("%d",&a);
 printf("Enter Values for B : ");
 scanf("%d",&b);
 (a>b)? printf("A is Greatest\n")  :  printf("B is Greatest\n");
 return 0;
}

Expected Output

Enter Values for A : 62
Enter Values for B : 119
B is Greatest

Explanation of the Program

  • The ternary operator does not always have to be assigned to a variable.
  • You can place function calls directly inside the true and false branches. The compiler will evaluate the condition (a &gt; b). If it is true, it executes the first printf. If false, it executes the second printf.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT