Conditional Statements
beginnerWhat you'll learn
- Write if/else chains that choose exactly one path.
- Use switch for many constant cases.
- Trace a condition and predict which branch runs.
Conditional statements let your program make decisions.
Problem
A student is marked out of 100 and you must print whether they passed. Writing both outcomes as separate lines of code gets wrong the moment the pass mark changes.
Goal: Decide Passed or Failed from one condition so the pass mark is written down exactly once.
READ marks
IF marks >= 40
PRINT "Passed"
ELSE
PRINT "Failed"A program makes the same decision with an if statement:
Every decision is a condition (true or false) plus what to do in each case. The rest of this note covers the different forms.
if Statement
if-else
if-else if-else
Nested if
Short Syntax (Single Statement)
Ternary Operator (Shortcut)
Equivalent to:
Flowchart of an if / else-if Ladder
Complete Program: Grading with if / else-if
Common mistakes: an = in a condition assigns instead of compares — if (x = 0) compiles but is almost always a bug; use ==.
Key takeaway: Always use braces even for single-line bodies, and chain mutually exclusive conditions with else-if for clear, readable decision logic.
Try it: Write a program that reads a temperature and prints "Freezing" if below 0, "Comfortable" between 18-24, and "Hot" above 30.