C Programming · Lesson 3 of 10 · Updated ·
Control Flow in C — if-else, switch, for, while, do-while, break, continue
Control statements decide which code runs and how many times.
1. if, else if, else
#include <stdio.h>
int main(void) {
int marks = 67;
if (marks >= 75) {
printf("Distinction\n");
} else if (marks >= 60) {
printf("First class\n");
} else if (marks >= 40) {
printf("Pass\n");
} else {
printf("Fail\n");
}
return 0;
}
First class
In C, any non-zero value is true and 0 is false. So if (5) runs and if (0) doesn't.
Trap:
if (x = 0)assigns 0 to x and is always false;if (x = 5)is always true. You meant==.
2. switch
#include <stdio.h>
int main(void) {
char op = '*';
int a = 6, b = 3;
switch (op) {
case '+': printf("%d\n", a + b); break;
case '-': printf("%d\n", a - b); break;
case '*': printf("%d\n", a * b); break;
case '/': printf("%d\n", a / b); break;
default: printf("unknown operator\n");
}
return 0;
}
18
switchworks with integers and characters (not strings or floats).- Without
break, execution falls through into the next case — a favourite output question.
3. The three loops
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) printf("%d ", i);
printf("\n");
int n = 4521, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
printf("reversed = %d\n", rev);
int k = 100;
do {
printf("do-while runs once (k = %d)\n", k);
} while (k < 10);
return 0;
}
1 2 3 4 5
reversed = 1254
do-while runs once (k = 100)
| Loop | Checks condition | Use when |
|---|---|---|
for | before each round | you know how many times |
while | before each round | repeat until something changes |
do-while | after each round → runs at least once | menus, input validation |
4. break and continue
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; /* skip even numbers */
if (i > 7) break; /* stop completely */
printf("%d ", i);
}
printf("\n");
return 0;
}
1 3 5 7
5. Nested loops and patterns
#include <stdio.h>
int main(void) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) printf(" ");
for (int j = 1; j <= 2 * i - 1; j++) printf("*");
printf("\n");
}
return 0;
}
*
***
*****
*******
The outer loop picks the row; inner loops print spaces, then stars for that row.
Prime numbers up to 30
#include <stdio.h>
int main(void) {
for (int n = 2; n <= 30; n++) {
int prime = 1;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) { prime = 0; break; }
}
if (prime) printf("%d ", n);
}
printf("\n");
return 0;
}
2 3 5 7 11 13 17 19 23 29
Common mistakes
- A semicolon right after the loop:
for (i = 0; i < 5; i++);— the body runs once, after the loop. - Forgetting
breakin switch cases. - Infinite while loops (the variable never changes).
Quick recap
- Non-zero is true, 0 is false; beware
=vs==. - switch on int/char; break to stop fall-through.
- for (known count), while (unknown), do-while (at least once).
- break exits the loop; continue skips to the next round.