Challenge - 5 Problems
Ternary Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested ternary operator
What is the output of this C code snippet?
C
int x = 5, y = 10; int result = x > y ? x : y > 7 ? y : x; printf("%d", result);
Attempts:
2 left
💡 Hint
Remember how nested ternary operators are evaluated from left to right.
✗ Incorrect
The expression evaluates as x > y ? x : (y > 7 ? y : x). Since x=5 is not greater than y=10, it checks y > 7 which is true, so result is y=10.
❓ Predict Output
intermediate2:00remaining
Ternary operator with side effects
What will be printed by this code?
C
int a = 3, b = 4; int c = (a > b) ? (a += 2) : (b += 3); printf("%d %d %d", a, b, c);
Attempts:
2 left
💡 Hint
Check which condition is true and how the variables change.
✗ Incorrect
Since a=3 is not greater than b=4, the else part runs: b += 3 makes b=7, c=7, a remains 3.
❓ Predict Output
advanced2:00remaining
Ternary operator with pointer dereference
What is the output of this code?
C
int x = 10, y = 20; int *p = (x > y) ? &x : &y; printf("%d", *p);
Attempts:
2 left
💡 Hint
Check which pointer is assigned based on the condition.
✗ Incorrect
Since x=10 is not greater than y=20, pointer p points to y, so *p is 20.
❓ Predict Output
advanced2:00remaining
Ternary operator with different types
What will this code print?
C
int a = 5; float b = 3.5; float c = (a > 3) ? a : b; printf("%.1f", c);
Attempts:
2 left
💡 Hint
The ternary operator promotes types to a common type.
✗ Incorrect
Since a=5 > 3, c is assigned a converted to float 5.0, so it prints 5.0.
🧠 Conceptual
expert2:00remaining
Ternary operator associativity
Consider the expression: int x = 1 ? 0 ? 2 : 3 : 4;
What is the value of x after this executes?
Attempts:
2 left
💡 Hint
Ternary operators associate right to left in C.
✗ Incorrect
Expression groups as: 1 ? (0 ? 2 : 3) : 4. Since 1 is true, evaluate (0 ? 2 : 3) which is 3, so x=3.