Home » C Loops – Master for, while, and do-while Statements with Examples

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

Loops in C programming allow you to execute a block of code multiple times without writing it again and again. They are essential for automation and efficient coding.

In this guide, you will learn for loop, while loop, and do-while loop in C with simple explanations and examples.

What are Loops in C?

Loops are used to repeat a set of instructions until a condition is met.

Benefits:

  • Reduce code repetition
  • Save time
  • Improve efficiency

for Loop in C

The for loop is used when you know how many times you want to run the loop.

Syntax

for (initialization; condition; increment/decrement) {
    // code
}

When to Use for Loop?

  • Fixed number of iterations
  • Counting tasks

Types of Loops in C

C provides three types of loops:

Loop TypeDescription
for loopUsed when number of iterations is known
while loopUsed when condition-based looping is needed
do-whileExecutes at least once
#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
Scroll to Top