Skip to study material
← Question index

QUESTION 62 · Operators

Explain the conditional operator ?: with an example.

5 marks

Answer in brief

The conditional operator ?: selects one of two expressions according to a condition. It is also called the ternary operator because it has three operands.

Syntax

condition ? expression_if_true : expression_if_false

First the condition is evaluated. A non-zero condition selects the first alternative. A zero condition selects the second alternative. Only the selected alternative is evaluated.

Example: larger value

Write maximum = a > b ? a : b;. If a = 12 and b = 7, the condition is true and maximum becomes 12. If a = 4 and b = 9, the condition is false and maximum becomes 9. Equal values also give the correct maximum.

Example: even or odd

The expression n % 2 == 0 ? "Even" : "Odd" selects the appropriate string for an integer n. It can be passed to printf or puts. Zero is even because its remainder on division by 2 is zero.

Advantages and important points

  1. Compact form: Useful for a short choice that produces one value.
  2. Readability: Use if-else when the alternatives contain several statements or become difficult to read.
  3. Grouping: Nested conditional operators group from right to left. Add parentheses for clarity.
  4. Types: The alternative expressions must have types permitted by C; C determines a suitable result type.

Diagram or flowchart

Evaluate a greater than b; a true condition selects a, and a false condition selects b; the selected value is assigned to larger.
Choosing a value with ?: · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int a = 15, b = 9;
    int larger = a > b ? a : b;
    printf("Larger = %d\n", larger);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Larger = 15

Key points

  • ?: is an expression that produces a selected value.
  • Only one alternative expression is evaluated.

Related exam questions

Topic matches from the supplied JNTUH papers. Marks below are the printed allocations for those questions.

  • September 2023 · Q3(b) · 4 marks

    What is the ternary operator? Write the syntax of switch-case.

    Paper P09 · page 1 · Combined subquestion: marks apply to its complete wording.
View all matching exam references →