Post

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

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

  1. Write a program that prints numbers 1 to 10 using a loop.
  2. Modify the program to print only even numbers.
  3. What is the difference between while and do-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!

Next Chapter → Functions – Divide and Conquer

This post is licensed under CC BY 4.0 by the author.