CS Engineering Gyan

Loops in C

Imagine having to print the numbers from 1 to 100 using nothing but individual printf statements. Not only would this involve writing a hundred nearly identical lines of code, but changing the range later would mean manually editing every single one of them. Loops exist precisely to eliminate this kind of repetitive, error-prone work by allowing a block of code to run multiple times automatically, based on a condition you define.

Loops are one of the concepts that make programming genuinely powerful, since they let a small amount of code accomplish tasks that would otherwise require enormous amounts of repeated instructions. Once you understand how loops work, you will find yourself using them constantly, whether you are processing arrays, validating user input, or performing repeated calculations.

In this tutorial, you will learn how the for loop, while loop, and do-while loop each work, how they differ from one another, how to use break and continue to control loop execution more precisely, how nested loops function, and how to recognize and avoid accidentally writing an infinite loop.


Why Loops Are Needed

Loops solve the problem of repeating a block of code without duplicating that code physically within the program. Instead of writing the same instruction over and over, a loop describes the instruction once, along with a condition that determines how many times it should run.

Example

#include <stdio.h>

int main() {

    int i;

    for (i = 1; i <= 5; i++) {

        printf("CS Engineering Gyan Tutorial %d\n", i);

    }

    return 0;

}

Output

CS Engineering Gyan Tutorial 1

CS Engineering Gyan Tutorial 2

CS Engineering Gyan Tutorial 3

CS Engineering Gyan Tutorial 4

CS Engineering Gyan Tutorial 5

This single loop replaces what would otherwise require five separate printf statements, and the behavior can be easily adjusted by simply changing the loop's condition.


The for Loop

The for loop is typically the first loop beginners learn, largely because it combines initialization, condition checking, and updating into a single, compact line, making it especially useful when the number of repetitions is known in advance.

Syntax

for (initialization; condition; update) {

    // code to repeat

}

Example

#include <stdio.h>

int main() {

    int totalViews = 0;

    int day;

    for (day = 1; day <= 7; day++) {

        totalViews += 500;

    }

    printf("Total views after one week: %d", totalViews);

    return 0;

}

Output

Total views after one week: 3500

The three parts of the for loop are evaluated in a specific order: the initialization runs once at the very beginning, the condition is checked before every repetition, and the update runs after each repetition completes, right before the condition is checked again.


The while Loop

The while loop is useful in situations where the number of repetitions is not known ahead of time, and instead depends entirely on a condition that may be influenced by user input or other changing data during execution.

Syntax

while (condition) {

    // code to repeat

}

Example

#include <stdio.h>

int main() {

    int subscribers = 8000;

    while (subscribers < 10000) {

        subscribers += 500;

        printf("Subscribers: %d\n", subscribers);

    }

    return 0;

}

Output

Subscribers: 8500

Subscribers: 9000

Subscribers: 9500

Subscribers: 10000

Here, the loop keeps running for as long as the subscriber count remains below the target, and it naturally stops the moment the condition becomes false, without needing to know in advance exactly how many repetitions will be required.


The do-while Loop

The do-while loop behaves almost identically to the while loop, with one important difference: the condition is checked after the loop body runs, rather than before. This guarantees that the loop body executes at least once, even if the condition turns out to be false immediately.

Syntax

do {

    // code to repeat

} while (condition);

Example

#include <stdio.h>

int main() {

    int attempt = 1;

    do {

        printf("Upload attempt %d\n", attempt);

        attempt++;

    } while (attempt <= 3);

    return 0;

}

Output

Upload attempt 1

Upload attempt 2

Upload attempt 3

This guaranteed first execution makes do-while particularly useful for situations like menu-driven programs, where an option needs to be displayed to the user at least once before checking whether they want to continue.


Comparing for, while, and do-while

Loop Type Condition Checked Best Suited For
for Before each repetition, combined with initialization and update. Situations where the number of repetitions is known in advance.
while Before each repetition. Situations where repetition depends on a condition that may change unpredictably.
do-while After each repetition. Situations where the loop body must run at least once regardless of the condition.

The break Statement

The break statement immediately stops a loop from continuing, regardless of what the loop's condition would otherwise evaluate to. It is commonly used when a specific situation is detected that makes further repetition unnecessary or undesirable.

Example

#include <stdio.h>

int main() {

    int i;

    for (i = 1; i <= 10; i++) {

        if (i == 6) {

            break;

        }

        printf("Processing item %d\n", i);

    }

    return 0;

}

Output

Processing item 1

Processing item 2

Processing item 3

Processing item 4

Processing item 5

Even though the loop was set up to run all the way to 10, the break statement forces it to exit early once the value of i reaches 6, skipping the remaining iterations entirely.


The continue Statement

Unlike break, which exits the loop entirely, continue skips only the remainder of the current iteration and moves directly to the next one, without terminating the loop as a whole.

Example

#include <stdio.h>

int main() {

    int i;

    for (i = 1; i <= 5; i++) {

        if (i == 3) {

            continue;

        }

        printf("Value: %d\n", i);

    }

    return 0;

}

Output

Value: 1

Value: 2

Value: 4

Value: 5

When i reaches 3, the continue statement skips the printf call for that particular iteration, but the loop still continues running normally for the remaining values.


Nested Loops

A nested loop is a loop placed inside another loop, allowing a program to handle repeated patterns that involve two or more dimensions, such as printing a grid or comparing every pair of elements within a dataset.

Example

#include <stdio.h>

int main() {

    int row, col;

    for (row = 1; row <= 3; row++) {

        for (col = 1; col <= 3; col++) {

            printf("(%d,%d) ", row, col);

        }

        printf("\n");

    }

    return 0;

}

Output

(1,1) (1,2) (1,3)

(2,1) (2,2) (2,3)

(3,1) (3,2) (3,3)

For every single repetition of the outer loop, the entire inner loop runs completely from start to finish, which is why nested loops are frequently used for tasks involving grids, tables, or comparisons between multiple sets of values.


Infinite Loops

An infinite loop occurs when a loop's condition never becomes false, causing it to run indefinitely unless deliberately interrupted using a break statement or by terminating the program manually. While infinite loops are sometimes created intentionally, they are far more often the result of a mistake.

Example

#include <stdio.h>

int main() {

    int count = 1;

    while (count <= 5) {

        printf("Count: %d\n", count);

        // count is never updated here, creating an infinite loop

    }

    return 0;

}

In this example, since the variable count is never increased inside the loop, the condition remains true forever, causing the program to print the same value endlessly until it is manually stopped. This highlights why it is essential to ensure that a loop's condition can eventually become false.


Best Practices When Writing Loops


Common Mistakes Beginners Make

Mistake Correct Practice
Forgetting to update the loop control variable, resulting in an infinite loop. Always ensure the variable used in the condition is updated somewhere within the loop body.
Placing a semicolon immediately after the for loop's parentheses by mistake. Avoid adding a semicolon right after the loop declaration, since it creates an empty loop body that runs with no effect.
Confusing the behavior of break and continue. Remember that break exits the loop entirely, while continue only skips the current iteration.
Using do-while when a while loop would be more appropriate. Reserve do-while specifically for cases where the loop body must execute at least once regardless of the condition.

Frequently Asked Interview Questions

  1. What is a loop in C?
    A loop is a control structure that repeats a block of code multiple times based on a specified condition.
  2. What is the main difference between a for loop and a while loop?
    A for loop combines initialization, condition checking, and updating in a single line, making it well suited when the number of repetitions is known in advance, while a while loop is better suited when repetition depends on a changing condition.
  3. What makes the do-while loop different from the while loop?
    The do-while loop checks its condition after executing the loop body, guaranteeing at least one execution, while the while loop checks its condition before running the body at all.
  4. What does the break statement do inside a loop?
    The break statement immediately terminates the loop, regardless of whether the loop's condition would otherwise still be true.
  5. What does the continue statement do inside a loop?
    The continue statement skips the remaining code in the current iteration and moves directly to the next iteration of the loop.
  6. What is a nested loop?
    A nested loop is a loop placed inside another loop, commonly used for tasks involving grids, tables, or comparisons between multiple sets of data.
  7. What is an infinite loop?
    An infinite loop is a loop whose condition never becomes false, causing it to run indefinitely unless deliberately stopped.
  8. What commonly causes an infinite loop by mistake?
    Forgetting to update the variable used in the loop's condition is one of the most common causes of an accidental infinite loop.
  9. Can a for loop be written without any of its three components?
    Yes, the initialization, condition, and update sections of a for loop can technically be left empty, though this requires careful handling to avoid creating an infinite loop.
  10. Why might a for loop unexpectedly execute with an empty body?
    Placing a semicolon directly after the for loop's parentheses creates an empty statement as the loop body, causing the intended code block to run only once after the loop finishes.
  11. When is a do-while loop particularly useful?
    It is particularly useful in situations such as menu-driven programs, where a set of options needs to be displayed at least once before checking whether the user wants to continue.
  12. How does a nested loop's execution order work?
    For every single repetition of the outer loop, the entire inner loop runs completely from its starting condition to its ending condition before the outer loop proceeds to its next repetition.

Summary

Loops transform repetitive, error-prone code into concise, flexible logic that can adapt to different amounts of repetition without requiring any structural changes. The for loop excels when the number of repetitions is known ahead of time, the while loop handles situations driven by changing conditions, and the do-while loop guarantees at least one execution regardless of the condition.

In this tutorial, you learned how each of these loop types works, how break and continue provide finer control over loop execution, how nested loops handle multi-dimensional repetition, and how to recognize and avoid accidentally creating an infinite loop. With loops now part of your toolkit, you are ready to explore arrays, which work especially well alongside loops when processing collections of related data.


← Previous: Conditional Statements Next: Arrays in C →

Home Visit Our YouTube Channel