Loop

M4-R5.1 · Chapter 4: Building IoT applications · 3 min read

 Loops in C 

  • A loop is a control structure that allows you to execute a block of code repeatedly based on a condition.
  • Loops are essential for automating repetitive tasks and keeping your code DRY (Don't Repeat Yourself).

1. Core Components of a Loop

  • Initialization: Setting a starting value for the loop counter variable.
  • Condition: A boolean expression that determines if the loop should continue running.
  • Update (Increment/Decrement): Modifying the loop counter variable after each iteration so the condition eventually becomes false.

2. Types of Loops in C

C provides three primary types of loops. They are categorized into two groups:

  • Entry-controlled loops: The condition is checked before entering the loop body (for, while).
  • Exit-controlled loops: The condition is checked after executing the loop body at least once (do...while).

A. The while Loop

Best used when you do not know the exact number of iterations beforehand, and the loop depends purely on a condition remaining true.

initialization;
while (condition) {
    // Code to be executed
    update;
}

Example:

#include <stdio.h>

int main() {
    int count = 1; // Initialization
    while (count <= 5) { // Condition
        printf("%d ", count);
        count++; // Update
    }
    return 0;
}

B. The for Loop

Best used when you know exactly how many times you want the loop to run. All three loop components are written on a single line, making it compact.

for (initialization; condition; update) {
    // Code to be executed
}

Example:

#include <stdio.h>

int main() {
    // Prints numbers 1 to 5
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    return 0;
}

C. The do...while Loop

Unlike the other loops, a do...while loop guarantees that the code block will execute at least once, even if the condition is false from the start.

initialization;
do {
    // Code to be executed
    update;
} while (condition); // Note the semicolon here!

Example:

#include <stdio.h>

int main() {
    int i = 10;
    do {
        printf("%d ", i); // This will print "10" even though 10 is not < 5
        i++;
    } while (i < 5);
    return 0;
}