Conditional Statements (if-else & switch)
int marks = 72;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else if (marks >= 60) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
Unlike Python's indentation-based blocks, C uses curly braces { } to group statements together. Indentation is purely for human readability in C — the compiler ignores it completely.
For simple two-way decisions, C offers a compact one-line alternative to if-else:
int age = 20;
char *status = (age >= 18) ? "Adult" : "Minor";
printf("%s\n", status);
The pattern is condition ? value_if_true : value_if_false. Use it for short, simple checks — for anything more complex, a regular if-else is more readable.
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
switch is often cleaner than a long chain of else if statements when comparing one variable against many exact values. default catches any value that didn't match a case, similar to Python's final else.
Without break, execution "falls through" into the next case automatically, running its code too, even if the value didn't match. This is occasionally used intentionally to group several cases together, but forgetting it by accident is a very common source of bugs.
If you omit break; at the end of a case, C keeps executing every case below it until it finds a break or reaches the end of the switch — regardless of whether those cases actually matched. This "fall-through" behavior is a deliberate C feature, but forgetting it accidentally is one of the most common beginner bugs.
Write a program using switch that converts a number from 1-7 into the corresponding day of the week, with a default case for invalid input.
#include <stdio.h>
int main() {
int day = 5;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
case 7: printf("Sunday\n"); break;
default: printf("Invalid day\n");
}
return 0;
}