Chapter 4: Control Flow – if, else, and Loops
Master control flow in C using if, else, and loops.
Chapter 4: Control Flow – if, else, and Loops
Table of Contents
- Table of Contents
- 4.1 if and else Statements
- 4.2 Loops: while, for, do-while
- 4.3 Exercises
- 4.4 Solutions
- 4.5 What’s Coming in the Next Chapter
4.1 if and else Statements
Control the flow of your program using if
and else
:
1
2
3
4
5
if (x > 0) {
printf("Positive\n");
} else {
printf("Not positive\n");
}
4.2 Loops: while, for, do-while
Loops let you repeat actions:
while
loop:1 2 3 4 5
int i = 0; while (i < 5) { printf("%d\n", i); i++; }
for
loop:1 2 3
for (int j = 0; j < 5; j++) { printf("%d\n", j); }
do-while
loop:1 2 3 4 5
int k = 0; do { printf("%d\n", k); k++; } while (k < 5);
4.3 Exercises
- Write a program that prints numbers 1 to 10 using a loop.
- Modify the program to print only even numbers.
- What is the difference between
while
anddo-while
?
4.4 Solutions
4.4.1 Solution 1
1
2
3
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
4.4.2 Solution 2
1
2
3
for (int i = 2; i <= 10; i += 2) {
printf("%d\n", i);
}
4.4.3 Solution 3
while
checks the condition before the loop body; do-while
checks after.
4.5 What’s Coming in the Next Chapter
Next, you’ll learn how to organize your code with functions!
This post is licensed under CC BY 4.0 by the author.