Skip to content
Solved Examples · Example 13

Q.Write a C program to illustrate the conditional operator.
#include<stdio.h>  
void main()  
{  
    int a=4, b=5, result1, result2;  
    result1 = a>b? a:b;  
    printf("The  result1=%d\h",result1);  
    result2 = a<b? a:b;  
    printf("The  result2=%d\h",result2);  
}  

Karnataka PUCTextbookLong· 3mImportance★★★★★est
42% · 64/154 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

[!TLDR]

The ternary operator ?: picks one of two values based on a condition; here it selects the larger value into result1 and the smaller into result2.

The conditional operator takes three operands and has the general form:

expression ? value1 : value2

If the expression is true the whole expression takes value1, otherwise it takes value2. Tracing with a = 4 and b = 5:

  • result1 = a>b ? a : b; : 4>5 is false, so result1 = b = 5.
  • result2 = a<b ? a : b; : 4<5 is true, so result2 = a = 4.

A complete, corrected version is:

#include <stdio.h>

int main(void)
{
    int a = 4, b = 5, result1, result2;
    result1 = a > b ? a : b;
    printf("The  result1=%d\n", result1);
    result2 = a < b ? a : b;
    printf("The  result2=%d\n", result2);
    return 0;
}
``` …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.