Control Flow Lesson 7 of 16
C if, else and switch
Make decisions in C with if, else if, else and switch-case, avoid the dangling-else and missing-break traps, and build a grade descriptor and menu.
Decisions let a program react differently to different situations. C has two decision tools: if/else for any condition, and switch for choosing among exact values.
if and else
#include <stdio.h>
int main(void) {
int grade = 72;
if (grade >= 75) {
printf("PASSED\n");
} else {
printf("FAILED\n");
}
return 0;
}
Output
FAILED
else if chains
#include <stdio.h>
int main(void) {
int grades[] = {95, 87, 81, 76, 70};
for (int i = 0; i < 5; i++) {
int g = grades[i];
printf("%d: ", g);
if (g >= 90) printf("Outstanding\n");
else if (g >= 85) printf("Very Satisfactory\n");
else if (g >= 80) printf("Satisfactory\n");
else if (g >= 75) printf("Fairly Satisfactory\n");
else printf("Did Not Meet Expectations\n");
}
return 0;
}
Output
95: Outstanding 87: Very Satisfactory 81: Satisfactory 76: Fairly Satisfactory 70: Did Not Meet Expectations
Only the first true branch runs, so the highest range goes first. (The for loop just tests several grades at once; loops are covered next.)
Combining conditions
#include <stdio.h>
int main(void) {
int year = 2028;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}
Output
2028 is a leap year.
Braces matter
Without braces, only one statement belongs to the if:
if (grade >= 75)
printf("PASSED\n");
printf("Congratulations!\n"); /* always runs! */
switch
#include <stdio.h>
int main(void) {
int choice = 2;
switch (choice) {
case 1:
printf("Pandesal - P25.00\n");
break;
case 2:
printf("Kape - P8.00\n");
break;
case 3:
printf("Itlog - P9.00\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
Output
Kape - P8.00
switch works with integer values and characters (case 'A':), not with decimals or strings. Each case should end with break, or execution "falls through" into the next case.
Intentional fall-through
#include <stdio.h>
int main(void) {
char grade = 'b';
switch (grade) {
case 'A': case 'a':
printf("Excellent\n");
break;
case 'B': case 'b':
printf("Good\n");
break;
case 'C': case 'c':
printf("Fair\n");
break;
default:
printf("Unknown grade\n");
}
return 0;
}
Output
Good
Stacked cases share the same code: uppercase and lowercase are both accepted.
A simple calculator
#include <stdio.h>
int main(void) {
double a = 15, b = 4;
char op = '/';
switch (op) {
case '+': printf("%.2f\n", a + b); break;
case '-': printf("%.2f\n", a - b); break;
case '*': printf("%.2f\n", a * b); break;
case '/':
if (b == 0) printf("Cannot divide by zero\n");
else printf("%.2f\n", a / b);
break;
default: printf("Unknown operator\n");
}
return 0;
}
Output
3.75
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04