Nearby lessons

42 of 124

C - Conditional (Ternary) Operator

Conditional (Ternary) Operator is one of the foundational topics in C programming. This lesson explains Conditional (Ternary) Operator (?:) and Program: check pass or fail with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Conditional (Ternary) Operator (?:)

This is a one-line shortcut for a simple if-else. It picks one of two values based on a condition.

In simple words: the ternary operator asks one yes/no question and hands you one of two answers. Read ? as "then" and : as "otherwise": marks >= 40 ? 'P' : 'F' → "if marks ≥ 40 then 'P', otherwise 'F'".
Example01
CCode Cell
1condition ? value_if_true : value_if_false

Program: check pass or fail

Example02
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks = 60;
6 char result;
7 
8 result = (marks >= 40) ? 'P' : 'F';
9 printf("Result: %c\n", result); // P
10 
11 int a = 10, b = 20;
12 int bigger = (a > b) ? a : b;
13 printf("Bigger of %d and %d is %d\n", a, b, bigger); // 20
14}
Output

Result: P
Bigger of 10 and 20 is 20
      
📝 Key Takeaways
  • Operators: arithmetic (+ - * / %), relational (== != < > <= >=), logical (&& || !), assignment (= += -= *= /= %=), ++ --, ternary ?:.
  • Each operator family has its own complete program — copy and run one at a time.
  • Integer division drops decimals: 5/2 = 2; use 5.0/2 for 2.5.
  • % gives the remainder and works only on integers.
  • a++ uses then increases; ++a increases then uses.
  • Ternary: condition ? value1 : value2.
  • Use brackets to control the order of evaluation.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1