Chapter 1 — Conditionals
`if / else if / else`, the ternary, and `switch` — the four ways C branches.
What you'll learn
- 1Write nested `if/else` cleanly.
- 2Use the ternary `? :` for short, value-producing branches.
- 3Choose `switch` when matching a single value to many cases.
- 4Watch out for fallthrough.
Core Concepts
1) `if / else if / else`
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else grade = 'F';Style tips: brace single-line bodies anyway; future edits won't bite you.
2) Ternary operator
int max = (a > b) ? a : b;Read as "condition ? value-if-true : value-if-false". Good for short value selection; avoid for side-effects.
3) `switch`
switch (op) {
case '+': r = a + b; break;
case '-': r = a - b; break;
default: r = 0;
}Each `case` must end with `break;` — otherwise execution **falls through** to the next case. Sometimes that's what you want; usually it's a bug.
4) Truthiness
In C, any **non-zero** integer is true; `0` is false.
if (x) { ... } // same as if (x != 0)Examples
Example 1 — `ex01_if.c`: simple grade classifier
int score = 85;
if (score >= 90) printf("A\n");
else if (score >= 80) printf("B\n");
else if (score >= 70) printf("C\n");
else printf("F\n");**Output**
BKey: only one branch runs — the **first** match.
Example 2 — `ex02_ternary.c`: max of two
int a = 7, b = 4;
int max = (a > b) ? a : b;
printf("max = %d\n", max);**Output**
max = 7Key: ternary returns a value; `if` is a statement. Use ternary for assignments.
Example 3 — `ex03_switch.c`: tiny calculator
char op = '+';
int a = 3, b = 4, r;
switch (op) {
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
default: r = 0;
}
printf("%d\n", r);**Output**
7Key: never forget `break` unless fallthrough is intentional.
Example 4 — `ex04_nested_if.c`: leap-year test
int y = 2024;
if (y % 400 == 0) printf("leap\n");
else if (y % 100 == 0) printf("not leap\n");
else if (y % 4 == 0) printf("leap\n");
else printf("not leap\n");**Output**
leapKey: order matters — most specific condition first.
Common mistakes
- **`=` instead of `==`** — assigns instead of compares.
- **Forgot `break`** — case fallthrough.
- **Misnested braces** — `else` binds to the nearest `if`.
- **Float equality** — `if (x == 0.1)` rarely works as expected.
Recap
- `if/else` for general branching; `switch` for one-value-many-cases.
- Brace every body even when one statement.
- Always `break` unless you actually want fallthrough.
Try it
cd src
gcc -std=c11 -Wall -o ex01 ex01_if.c && ./ex01
gcc -std=c11 -Wall -o ex02 ex02_ternary.c && ./ex02
gcc -std=c11 -Wall -o ex03 ex03_switch.c && ./ex03
gcc -std=c11 -Wall -o ex04 ex04_nested_if.c && ./ex04💻 Examples
Compilable, runnable examples — see the output yourself.
#include <stdio.h>
int main(void) {
int score;
printf("Score (0-100): ");
scanf("%d", &score);
if (score < 0 || score > 100) {
printf("Out of range.\n");
return 1;
}
if (score >= 90) printf("Grade: A\n");
else if (score >= 80) printf("Grade: B\n");
else if (score >= 70) printf("Grade: C\n");
else if (score >= 60) printf("Grade: D\n");
else printf("Grade: F\n");
return 0;
}
B#include <stdio.h>
int main(void) {
int a, b;
printf("Two ints: ");
scanf("%d %d", &a, &b);
int max = (a > b) ? a : b;
int min = (a < b) ? a : b;
const char *parity = (a % 2 == 0) ? "even" : "odd";
printf("max: %d\n", max);
printf("min: %d\n", min);
printf("a is %s\n", parity);
return 0;
}
max = 7#include <stdio.h>
int main(void) {
double a, b, result = 0;
char op;
printf(" (: 3 + 4): ");
scanf("%lf %c %lf", &a, &op, &b);
int ok = 1;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/':
if (b == 0) { printf("Cannot divide by zero.\n"); ok = 0; }
else result = a / b;
break;
default:
printf(" : %c\n", op);
ok = 0;
}
if (ok) printf(": %.3f\n", result);
return 0;
}
7#include <stdio.h>
/* : 4 , 100 , 400 */
int main(void) {
int year;
printf("Year: ");
scanf("%d", &year);
int leap;
if (year % 4 == 0) {
if (year % 100 == 0) {
leap = (year % 400 == 0);
} else {
leap = 1;
}
} else {
leap = 0;
}
printf("%d %s\n", year, leap ? "is a leap year." : "is not a leap year.");
return 0;
}
leap📝 Exercises
Try them yourself first, then open the solution to compare.
Problem 1 (hw01.c)
Goal: Read a month (1-12) and print the season.
- Filename: hw01.c
▶Toggle solution
#include <stdio.h>
int main(void) {
int a, b, c;
printf(" Enter int: ");
scanf("%d %d %d", &a, &b, &c);
int max = a;
if (b > max) max = b;
if (c > max) max = c;
printf("max: %d\n", max);
return 0;
}
Problem 2 (hw02.c)
Goal: Implement rock-paper-scissors logic with `switch`.
- Filename: hw02.c
▶Toggle solution
#include <stdio.h>
int main(void) {
int age;
printf("Age: ");
scanf("%d", &age);
if (age < 0) printf("Invalid input\n");
else if (age <= 7) printf("Infant\n");
else if (age <= 13) printf("Child\n");
else if (age <= 19) printf("Teen\n");
else if (age <= 64) printf("Adult\n");
else printf("Senior\n");
return 0;
}
Problem 3 (hw03.c)
Goal: Read weight (kg) and height (m), compute BMI = w / h², classify (underweight/normal/overweight/obese).
- Filename: hw03.c
▶Toggle solution
#include <stdio.h>
int main(void) {
int month;
printf("Month (1-12): ");
scanf("%d", &month);
int days;
switch (month) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
days = 31; break;
case 4: case 6: case 9: case 11:
days = 30; break;
case 2:
days = 28; break;
default:
printf("Invalid input\n");
return 1;
}
printf("%d has %d days.\n", month, days);
return 0;
}
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗