AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumcternary

~75s

A nested conditional expression

What does this C program print?

#include <stdio.h>

int main(void) {
    int x = 3;
    printf("%d", x > 2 ? x > 4 ? 100 : 200 : 300);
    return 0;
}
Show the answer and the worked solution

Correct answer: C.

200

Worked solution

  1. The expression groups as x > 2 ? (x > 4 ? 100 : 200) : 300.
  2. x = 3, so x > 2 is true and the outer conditional selects its middle operand.
  3. Inside that, x > 4 is false, so the result is 200.

Answer: 200.

The idea

?: is right-associative, so an unbracketed chain nests inside the previous true branch. Adding the brackets by hand converts the puzzle into an ordinary if / else chain.

Shortcut. The inner ?: nests inside the true branch: 3 passes x > 2 and fails x > 4, so the value is the inner false branch, 200.

Common trap. 100 is picked by stopping at the first true test, x > 2, and taking the first number after a ?, without evaluating the inner x > 4.

A nested conditional expression — Aptitude Question

A nested conditional expression: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

int main(void) {
    int x = 3;
    printf("%d", x > 2 ? x > 4 ? 100 : 200 : 300);
    return 0;
}

Options

  1. 3
  2. 100
  3. 200
  4. 300
Show the answer and the worked solution

Correct answer: C. 200

Worked solution

  1. The expression groups as x > 2 ? (x > 4 ? 100 : 200) : 300.
  2. x = 3, so x > 2 is true and the outer conditional selects its middle operand.
  3. Inside that, x > 4 is false, so the result is 200.

Answer: 200.

The idea

?: is right-associative, so an unbracketed chain nests inside the previous true branch. Adding the brackets by hand converts the puzzle into an ordinary if / else chain.

Shortcut. The inner ?: nests inside the true branch: 3 passes x > 2 and fails x > 4, so the value is the inner false branch, 200.

Common trap. 100 is picked by stopping at the first true test, x > 2, and taking the first number after a ?, without evaluating the inner x > 4.

All Programming Fundamentals questions · placement mock tests