C in 100 Seconds: If/Else | Episode 5
Video: C in 100 Seconds: If Else — Grade Calculator in 14 Lines | Episode 5 by Taught by Celeste AI - AI Coding Coach
Watch full page →If/Else — Making Decisions in C
C in 100 Seconds, Episode 5
Programs need to make choices. In C, the if statement is how you branch your code based on conditions.
Basic If/Else If/Else
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
C evaluates conditions top to bottom. The first one that's true wins, and the rest are skipped. If nothing matches, else catches everything that's left.
The Ternary Operator
For simple two-way decisions, C has a one-liner:
int age = 20;
printf(age >= 18 ? "Adult\n" : "Minor\n");
The syntax is condition ? value_if_true : value_if_false. It's compact, but don't nest them — readability drops fast.
How C Sees Conditions
C doesn't have a boolean type in the traditional sense. Conditions evaluate to integers: 0 is false, anything else is true. So if (1) always executes, and if (0) never does.
Why Does This Matter?
Every non-trivial program needs branching. Whether you're validating input, checking error codes, or routing logic, if/else is the foundation. The ternary operator is a shortcut for when the branch is simple enough to fit in one expression.
Full Code
#include <stdio.h>
int main() {
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
int age = 20;
printf(age >= 18 ? "Adult\n" : "Minor\n");
return 0;
}
Compile and Run
gcc ifelse.c -o ifelse
./ifelse
Next episode: Switch — a cleaner way to handle multiple specific values.
Student code: github.com/GoCelesteAI/c-in-100-seconds/episode05