Loops in C

A loop is a programming construct that repeats a block of code multiple times until a specified condition is met. Without loops, if a task needed to be done 100 times, it would require writing the same code 100 times. Loops solve this problem elegantly.

C provides three types of loops:

  1. The for loop
  2. The while loop
  3. The do-while loop

The for Loop

The for loop is used when the number of iterations is known in advance. It combines initialization, condition checking, and update in a single line.

Syntax


for (initialization; condition; update)
{
    // code to repeat
}

How for Loop Works

  1. Initialization: Sets the starting value (runs only once).
  2. Condition: Checked before every iteration. If true, loop runs. If false, loop stops.
  3. Update: Runs after every iteration to move toward the end condition.

Example — Print 1 to 5


#include <stdio.h>

int main()
{
    int i;

    for (i = 1; i <= 5; i++)
    {
        printf("%d\n", i);
    }

    return 0;
}

Output


1
2
3
4
5

Example — Sum of First 10 Natural Numbers


#include <stdio.h>

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

    for (i = 1; i <= 10; i++)
    {
        sum += i;  // sum = sum + i
    }

    printf("Sum = %d\n", sum);  // Sum = 55

    return 0;
}

Example — Print Multiplication Table


#include <stdio.h>

int main()
{
    int n;

    printf("Enter a number: ");
    scanf("%d", &n);

    for (int i = 1; i <= 10; i++)
    {
        printf("%d x %d = %d\n", n, i, n * i);
    }

    return 0;
}

Sample Output


Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

for Loop with Decrement


#include <stdio.h>

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

Output


5 4 3 2 1

Nested for Loops

A loop inside another loop is called a nested loop. For each iteration of the outer loop, the inner loop runs completely.


#include <stdio.h>

int main()
{
    // Print a 3x3 star pattern
    for (int i = 1; i <= 3; i++)
    {
        for (int j = 1; j <= 3; j++)
        {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}

Output


* * * 
* * * 
* * * 

The while Loop

The while loop is used when the number of iterations is not known in advance, but the loop should continue as long as a condition remains true. The condition is checked before entering the loop body.

Syntax


while (condition)
{
    // code to repeat
    // update statement to avoid infinite loop
}

Example — Print 1 to 5 Using while


#include <stdio.h>

int main()
{
    int i = 1;

    while (i <= 5)
    {
        printf("%d\n", i);
        i++;  // update to avoid infinite loop
    }

    return 0;
}

Output


1
2
3
4
5

Example — Read Numbers Until 0 is Entered


#include <stdio.h>

int main()
{
    int num;
    int sum = 0;

    printf("Enter numbers (0 to stop):\n");
    scanf("%d", &num);

    while (num != 0)
    {
        sum += num;
        scanf("%d", &num);
    }

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

    return 0;
}

Sample Interaction


Enter numbers (0 to stop):
5
10
3
0
Sum = 18

The do-while Loop

The do-while loop is similar to the while loop, but there is one key difference: the condition is checked after executing the loop body. This guarantees that the loop body executes at least once, even if the condition is false from the beginning.

Syntax


do
{
    // code to execute
} while (condition);

Example — Print 1 to 5 Using do-while


#include <stdio.h>

int main()
{
    int i = 1;

    do
    {
        printf("%d\n", i);
        i++;
    } while (i <= 5);

    return 0;
}

Output


1
2
3
4
5

do-while Guarantees One Execution


#include <stdio.h>

int main()
{
    int i = 10;  // condition is already false

    do
    {
        printf("This runs once even if condition is false.\n");
        i++;
    } while (i < 5);  // false from start

    return 0;
}

Output


This runs once even if condition is false.

Practical Use — Input Validation Menu


#include <stdio.h>

int main()
{
    int choice;

    do
    {
        printf("\n--- Menu ---\n");
        printf("1. Add\n");
        printf("2. Subtract\n");
        printf("3. Exit\n");
        printf("Enter choice: ");
        scanf("%d", &choice);
    } while (choice != 3);

    printf("Goodbye!\n");

    return 0;
}

Comparison of Loops

Featurefor Loopwhile Loopdo-while Loop
When to useKnown number of iterationsCondition-based, unknown countMust run at least once
Condition checkedBefore each iterationBefore each iterationAfter each iteration
Minimum executions001
InitializationInside loop headerOutside loopOutside loop

break Statement

The break statement immediately exits the loop (or switch) when encountered. The remaining iterations are skipped and control moves to the next statement after the loop.


#include <stdio.h>

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        if (i == 6)
        {
            break;  // exit loop when i is 6
        }
        printf("%d ", i);
    }
    printf("\nLoop ended.\n");

    return 0;
}

Output


1 2 3 4 5 
Loop ended.

continue Statement

The continue statement skips the current iteration and moves to the next one. The rest of the loop body after continue is not executed for that iteration.


#include <stdio.h>

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        if (i % 2 == 0)
        {
            continue;  // skip even numbers
        }
        printf("%d ", i);  // only odd numbers are printed
    }
    printf("\n");

    return 0;
}

Output


1 3 5 7 9 

Infinite Loop

A loop that never ends is called an infinite loop. This happens when the condition always evaluates to true. It can be useful in some applications (like always-on server software), but usually should be avoided by ensuring the loop variable is updated correctly.


// Infinite for loop
for (;;)
{
    printf("Running forever...\n");
}

// Infinite while loop
while (1)
{
    printf("This never stops.\n");
}

To exit an infinite loop intentionally, use a break statement inside.

Summary

Loops are fundamental to programming — they eliminate code repetition and allow programs to handle any number of inputs or operations efficiently. The for loop is best when the number of repetitions is known. The while loop is ideal when the loop depends on a condition. The do-while loop ensures the code runs at least once before checking the condition. break exits a loop early, and continue skips to the next iteration. Mastering loops is one of the most important skills in learning C programming.

Leave a Comment

Your email address will not be published. Required fields are marked *