C - Looping Statements

Looping statements allow you to execute a block of code repeatedly based on a condition. C provides three main types of loops: for, while, and do-while.

Prerequisites

Learning Objectives

  • Choose between for/while/do-while appropriately.
  • Write correct loop conditions and updates.

Types of Loops

  • for loop: Used when the number of iterations is known.
  • while loop: Used when the number of iterations is not known in advance.
  • do-while loop: Similar to while, but guarantees at least one execution.

Example: for loop

#include <stdio.h>

int main(void) {
    for (int i = 0; i < 5; i++) {
        printf("i = %d\n", i);
    }
    return 0;
}

Output:

i = 0
i = 1
i = 2
i = 3
i = 4

Example: while loop

#include <stdio.h>

int main(void) {
    int i = 5;
    while (i > 0) {
        printf("i = %d\n", i--);
    }
}

Example: do-while loop

#include <stdio.h>

int main(void) {
    int i = 0;
    do {
        printf("i = %d\n", i);
        i++;
    } while (i < 1);
}

Common Pitfalls

  • Off-by-one errors in loop bounds.
  • Forgetting to update the loop variable, causing infinite loops.

Summary

Loops are essential for automating repetitive tasks in C. Choose the appropriate loop based on your use case.

Checks for Understanding

  1. When does a do-while loop stop?
  2. What’s the difference between i++ and ++i in a loop?
Show answers
  1. When its condition becomes false—after executing the body at least once.
  2. As expressions they differ in value; in loop control either works similarly for simple increments.