Conditionals (if-else & switch)
Conditionals execute specific code pathways depending on whether boolean parameters resolve to true or false. In C, any non-zero value represents true, and zero represents false.
1 True and False in C (Truthy vs Falsy)
C historically does not have a native primitive boolean type (though `<stdbool.h>` was added in C99). Instead, C evaluates conditions numerically:
- False: Represented by the integer value `0`.
- True: Represented by **any non-zero value** (both positive and negative numbers like `1`, `5`, `-12`).
2 Logical Structures and Switch Fall-through
The conditional statements use `if`, `else if`, and `else` keywords. In switch-case blocks, omitting a `break` statement causes execution to "fall through" and execute subsequent case blocks without validation. Let's test this behavior:
C — If statements and Switches
▶ Run Code
#include <stdio.h>
int main() {
int age = 17;
int hasPermit = 1; // 1 is true in C
if (age >= 18) {
printf("Eligible for driving license.\n");
} else if (age >= 16 && hasPermit) {
printf("Eligible to drive with supervision.\n");
} else {
printf("Not eligible to drive.\n");
}
// Switch case with break checks
char grade = 'B';
switch(grade) {
case 'A':
printf("Excellent work!\n");
break;
case 'B':
printf("Good progress!\n");
// No break! Fall-through will execute next case too!
case 'C':
printf("Passed!\n");
break;
default:
printf("Try again!\n");
}
return 0;
}
3 Code Challenge
Challenge: Write a nested conditional checking if a year is a leap year. A year is a leap year if it is divisible by 4, except for years divisible by 100 unless they are also divisible by 400. Print the leap year status for `2026` and `2024`.