Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C Programming Tutorial / Chapter 2: Operators & Control Flow
C ⏱ 12 min read

Loops in C: for, while, and do-while

Loops automate repetitive instructions, iterating over array indices and data streams.

What is it?

C provides three loop structures: 1. `for`: Deterministic loop with initialization, condition, and increment in one line. 2. `while`: Pre-test loop (checks condition before running body). 3. `do-while`: Post-test loop (guarantees body runs at least once).

Why is it used?

Array traversal, numeric algorithms, mathematical summations, and polling loops.

Detailed Explanation

Loop Mechanics: • `for (init; condition; update)`: Standard for counting loops. • `while (condition)`: Ideal when number of iterations is unknown. • `do { ... } while (condition);`: Notice the mandatory semicolon `;` after the `while` in `do-while`! Perfect for interactive menus that must present at least once.

Syntax Structure

Syntax Blueprint
for (int i = 0; i < n; i++) { ... }
while (cond) { ... }
do { ... } while (cond);

Code Example

C Code
#include <stdio.h>

int main() {
    // 1. for loop: Generating powers of 2
    printf("=== Powers of 2 ===\n");
    int power = 1;
    for (int i = 0; i <= 6; i++) {
        printf("2^%d = %d\n", i, power);
        power *= 2;
    }
    
    // 2. while loop: Sum of digits of 456 (4+5+6 = 15)
    int number = 456;
    int sum = 0;
    int temp = number;
    
    while (temp > 0) {
        sum += temp % 10; // Extract last digit
        temp /= 10;       // Remove last digit
    }
    printf("\nSum of digits of %d = %d\n", number, sum);
    
    // 3. do-while loop: Guarantees at least 1 iteration
    int attempts = 0;
    do {
        attempts++;
    } while (attempts < 1);
    printf("Total attempts executed: %d\n", attempts);
    
    return 0;
}

Explanation of the Code

• `for` loop calculates powers cleanly. • `while` loop extracts digits using `% 10` and `/ 10`. • `do-while` executes body once before verifying condition.

Expected Output

=== Powers of 2 === 2^0 = 1 2^1 = 2 2^2 = 4 2^3 = 8 2^4 = 16 2^5 = 32 2^6 = 64 Sum of digits of 456 = 15 Total attempts executed: 1

Real-World Application

Used across graphics rasterizers, cryptographic hashing algorithms (SHA-256), and file buffers.

Common Mistakes to Avoid

• Off-by-one errors (looping `i <= n` instead of `i < n` when traversing zero-indexed arrays). • Forgetting the semicolon `;` at the end of a `do { ... } while (cond);` statement.

Quick Practice Challenge

Print numbers from 10 down to 1 using a countdown `for` loop.

Key Takeaways

• Use `for` when iteration count is known. • Use `while` for condition-driven iterations. • `do-while` guarantees at least one execution.