C Loops: for, while, do-while – Complete Guide

Loops in C are used to execute a block of code repeatedly as long as a given condition is true. C supports three primary types of loops:

  1. for loop – when you know how many times to loop

  2. while loop – when you don’t know how many times to loop

  3. do-while loop – when the loop must run at least once

C for Loop

Syntax:

 
for (initialization; condition; update) {
// Code block to execute
}

 Example:

#include <stdio.h>

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

 Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

C while Loop

Syntax:

while (condition) {
// Code block
}

Example:

#include <stdio.h>

int main() {
    int i = 1;
    while (i <= 5) {
        printf("Count: %d\n", i);
        i++;
    }
    return 0;
}

 Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

C do-while Loop

This loop always executes at least once, even if the condition is false on the first check.

Syntax:

do {
// Code block
} while (condition);

 Example:

 
#include <stdio.h>

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

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Loop Comparison Table

Loop TypeCondition CheckedGuaranteed One ExecutionBest For
forBefore loopNoKnown number of iterations
whileBefore loopNoUnknown number, pre-condition
do-whileAfter loopYesAt least one execution needed

Best Practices

TipBenefit
Avoid infinite loopsUse proper conditions
Use break and continue wiselyImprove control and logic clarity
Comment complex loopsImproves code readability

Common Mistakes

MistakeExplanation
Forgetting to update loop counterLeads to infinite loop
Using = instead of ==Assignment instead of comparison
Skipping {} for multi-line loopsOnly the first line is considered

Real-Life Example: Sum of Numbers

#include <stdio.h>

int main() {
    int sum = 0, i = 1;

    while (i <= 100) {
        sum += i;
        i++;
    }

    printf("Sum = %d\n", sum);
    return 0;
}

 Output:

Sum = 5050