C - Conditional Statements
Conditional statements allow your program to make decisions based on boolean expressions.
Learning Objectives
- Use
if
,if-else
, andelse if
ladders. - Choose between
if
chains andswitch
.
Prerequisites
if / else
#include <stdio.h>
int main(void) {
int x = 3;
if (x > 0) {
printf("positive\n");
} else {
printf("non-positive\n");
}
}
else if ladder
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else grade = 'D';
switch
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
default: printf("unknown op\n"); break;
}
Common Pitfalls
- Forgetting
break
inswitch
causes fall-through. - Using assignment
=
instead of comparison==
in conditions.
Checks for Understanding
- When would you prefer
switch
overif-else
? - What happens without
break
in aswitch
case?
Show answers
- When comparing the same variable to many constant values (e.g., chars, small ints).
- Execution "falls through" into the next case.