Loops in C: A Complete Guide

Published: 16 Apr 2025 | Reading Time: 12 min read

Introduction

Try creating a program in C that prints numbers one to hundred. Would you write a hundred lines of code? Right? Not at all. That's where loops in C come into play. Loops are one of the most fundamental programming concepts, enabling you to run a block of code repeatedly until the specified condition is met. There are three types of loops used in the C language. What if you want to skip specific iterations or need to end a loop early? This is where loop control statements like goto, continue, and break are necessary.

You will learn everything a C programmer should know about loops in C and loop control statements in this detailed guide.

Table of Contents

What are Loops in C?

In C, loops are control structures that enable you to repeatedly run a piece of code until a predetermined condition is satisfied. By automating repetitive processes improves the efficiency and maintainability of your code. Loops are necessary for tasks like processing user input, iterating across arrays, and resolving issues that call for repetitive computations.

How Does a Loop Work in C?

A code block is continually executed if a given condition is true in a loop. After the condition is changed to false, the loop ends, and the program moves on to the following statement.

Advantages of Looping

Looping is one of the fundamental concepts in programming that allows a set of instructions to be executed repeatedly until a specific condition is met. Here are some key advantages of using loops:

1. Saves Time and Effort

Loops eliminate the need to write repetitive code. Instead of repeating the same instructions multiple times, a loop can execute them automatically, saving both time and effort for the programmer.

2. Improves Code Efficiency

With loops, programs can handle large volumes of data and perform tasks more efficiently. This makes your code cleaner, more compact, and easier to manage.

3. Enhances Flexibility and Scalability

Loops allow your program to adapt to changes in data size. Whether you're processing 10 items or 10,000, loops make your code scalable without rewriting logic.

4. Supports Automation and Reusability

Loops enable automation of repetitive tasks such as calculations, data processing, and user input validation. This makes your code more reusable and reduces the chances of manual errors.

5. Facilitates Better Logic Implementation

Many algorithms rely on iteration to function correctly. Loops are essential in implementing logic for searching, sorting, traversing data structures, and more.

Types of Loops in C

In C programming, loops are essential constructs that allow the execution of a block of code multiple times based on a specified condition. This repetition facilitates tasks such as iterating over data structures, performing calculations, and automating repetitive operations. The primary types of loops in C are:

1. Entry-Controlled Loops

2. Exit-Controlled Loop

Let's delve into each type, clearly explaining their algorithms, corresponding C code, detailed explanations, and expected outputs.

1. Entry-Controlled Loops

In entry-controlled loops, the loop's condition is evaluated before executing the loop's body. The loop body is not executed if the condition is initially evaluated as false.

For Loop (Entry-Controlled Loop)

The for loop is a control structure that allows code to be executed repeatedly for a known number of iterations. As long as the condition is true, the loop runs. It has three parts: initialization, condition, and update.

  1. Initialization: Executed once at the beginning of the loop.
  2. Condition: Evaluated before each iteration. The loop continues if it is true and stops if it is false.
  3. Update: Executed at the end of each iteration.

Algorithm

  1. Initialize a loop control variable with a starting value.
  2. Check the condition before each iteration. If the condition is false, exit the loop.
  3. Execute the statements inside the loop body if the condition is true.
  4. Update the loop control variable (e.g., increment or decrement).
  5. Repeat steps 3-5 until the condition becomes false.
  6. End

C for Loop Syntax

for (initialization; condition; update) {
    // Code to be executed
}

C for Loop Example

#include <stdio.h>
int main() {
    // Using for loop to print numbers from 1 to 5
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    return 0;
}

Explanation

Output

1 2 3 4 5

Example Program to Calculate the Sum of First 30 Natural Numbers

Here's a simple example program in C to calculate the sum of the first 30 natural numbers using a for loop.

#include <stdio.h>

int main() {
    int sum = 0;

    // Loop from 1 to 30
    for (int i = 1; i <= 30; i++) {
        sum += i; // Add current number to sum
    }

    // Print the result
    printf("The sum of the first 30 natural numbers is: %d\n", sum);

    return 0;
}

Explanation

  1. We start by declaring a variable sum and set it to 0. This variable will store the total sum.
  2. The for loop runs from 1 to 30, the first 30 natural numbers.
  3. In each loop iteration, the current number i is added to the sum. For example, in the first iteration, sum = 0 + 1, in the second, sum = 1 + 2, and so on.
  4. Once the loop completes, all numbers from 1 to 30 have been added together.
  5. Finally, the program prints the result using printf().

Output

The sum of the first 30 natural numbers is: 465

While Loop in C

The while loop is used when the number of iterations is not known in advance. It first checks the condition, and if it's true, it executes the loop body. The loop continues until the condition becomes false. It is also called a pre-tested loop.

Algorithm

  1. Initialization: Set up a loop control variable to a starting value.
  2. Condition Evaluation: Check if the loop control variable meets the specified condition before each iteration.
  3. If the condition is true, execute the loop body.
  4. Update: Modify the loop control variable.
  5. Repeat steps 2-4 until the condition evaluates to false.

Syntax of while Loop

while (condition) {
    // Code to be executed
}

C Code Example for Printing Numbers from 1 to 5 using a While Loop

#include <stdio.h>
int main() {
    int i = 0; // Initialization
    while (i <= 5) { // Condition Evaluation
        printf("%d ", i);
        i++; // Update
    }
    return 0;
}

Explanation

Output

0 1 2 3 4 5

Example using Infinite Loop

#include <stdio.h>
int main() {
    // Infinite loop using while
    while (1) {
        printf("This is an infinite loop!\n");
    }
    return 0;
}

Explanation

2. Exit-Controlled Loop

In exit-controlled loops, the loop's body is executed first, and the condition is evaluated after the execution. This guarantees that the loop body executes at least once, regardless of the condition's initial state.

Do-while Loop in C

The do-while loop guarantees that the body executes at least once before checking the condition. It is useful when the loop must execute at least once, regardless of the condition. It is also called post-tested loop.

Syntax of do-while Loop

do {
    // Code to be executed
} while (condition);

Example: do-while Loop in C

#include <stdio.h>
int main() {
    int i = 1; // Initialization
    do {
        printf("%d ", i);
        i++; // Update
    } while (i <= 5); // Condition Evaluation
    return 0;
}

Explanation

1. Initialization

2. do Block Execution

3. Condition Evaluation (After Block)

4. Loop Repeats Until

Output

1 2 3 4 5

Comparison Between for, while and do-while Loops

Here are the key differences between for, while and do-while loops:

Aspect for Loop while Loop do-while Loop
Definition A loop that integrates initialization, condition checking, and updating within a single statement. Ideal when the number of iterations is predetermined. A loop that evaluates a condition before each iteration and continues to execute as long as the condition remains true. A loop that executes the code block once before evaluating the condition, ensuring at least one execution regardless of the condition.
Syntax for (initialization; condition; update) { /* code */ } while (condition) { /* code */ } do { /* code */ } while (condition);
Initialization Performed once at the start within the loop statement. Must be done explicitly before entering the loop. Must be done explicitly before entering the loop.
Condition Evaluation Checked before each iteration; if false initially, the loop body may not execute at all. Checked before each iteration; if false initially, the loop body does not execute. Checked after the loop body executes; thus, the loop body always executes at least once.
Update Typically included within the loop statement and executed after each iteration. Must be handled explicitly within the loop body. Must be handled explicitly within the loop body.
Entry/Exit Control Entry-controlled loop (condition is evaluated before entering the loop body). Entry-controlled loop (condition is evaluated before entering the loop body). Exit-controlled loop (condition is evaluated after the loop body executes).
Loop Body Execution May not execute at all if the condition is false initially. May not execute at all if the condition is false initially. Executes at least once, regardless of the initial condition.
Use Cases Suitable when the number of iterations is known beforehand, such as iterating over arrays or fixed ranges. Offers a compact and structured way to write loops, encapsulating all loop control elements in a single line and enhancing readability for simple loops. Ideal when the number of iterations isn't predetermined and depends on dynamic conditions. Useful when the loop must execute at least once, such as in menu-driven programs requiring user interaction.
Readability It offers a compact and structured way to write loops, encapsulating all loop control elements in a single line and enhancing readability for simple loops. Provides flexibility but may require careful management of loop control variables, potentially affecting readability. Ensures at least one execution, which can be beneficial but might lead to unintended behavior if not handled properly.
Common Pitfalls Overlooking the update statement can lead to infinite loops; modifying loop control variables inside the loop body can cause unexpected behavior. Forgetting to update the loop control variable or incorrect condition evaluation can result in infinite loops. Misunderstanding that the loop executes at least once can lead to errors if the initial condition is not intended without a condition check. Slightly less efficient in scenarios where the loop body should not execute if the condition is false initially, due to mandatory first execution.
Performance Generally efficient for scenarios with a known number of iterations; minimal overhead due to compact structure. It can be efficient, but may introduce overhead if the loop control variables are not managed properly. Slightly less efficient in scenarios where the loop body should not execute if the condition is false initially, due to mandatory first execution.
Example for (int i = 0; i < 5; i++) { printf("%d ", i); } int i = 0; while (i < 5) { printf("%d ", i); i++; } int i = 0; do { printf("%d ", i); i++; } while (i < 5);

Infinite Loops in C

A loop becomes an infinite loop when its condition never evaluates to false. An infinite loop is a loop that continues to execute indefinitely because it lacks a terminating condition, the termination condition is never satisfied, or the loop is directed to start over from the beginning.

Example using For Infinite Loop

An infinite loop runs endlessly until it is forcefully stopped. Below is an example of creating an infinite loop using the for statement.

#include <stdio.h>
int main() {
    // Infinite for loop
    for (;;) {
        printf("This is an infinite loop!\n");
    }

    return 0;
}

Explanation

Output

This is an infinite loop!

Example of using Do-While Infinite Loop

In C programming, a do-while loop can be intentionally crafted to run indefinitely by setting its condition to always evaluate as true. Below is an example explaining this concept:

#include <stdio.h>
int main() {
    int count = 1; // Initialize a counter variable

    do {
        printf("Iteration: %d\n", count);
        count++;

        // To prevent the loop from running indefinitely during demonstration,
        // we'll break out of the loop after 10 iterations.
        if (count > 10) {
            break;
        }
    } while (1); // The condition is always true, creating an infinite loop

    printf("Exited the loop after 10 iterations.\n");
    return 0;
}

Explanation

Note: In practical scenarios, infinite loops are generally avoided unless there's a specific requirement, such as in embedded systems or server applications, where the program needs to run continuously. Always ensure there's a mechanism to exit the loop to prevent the program from becoming unresponsive.

Output

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
Iteration: 7
Iteration: 8
Iteration: 9
Iteration: 10
Exited the loop after 10 iterations.

Best Practices for Using Loops in C

Using loops efficiently can make your C programs more effective and easier to read. Here are some practical tips to follow while working with loops in C:

1. Choose the Right Loop Type

If you are aware of the total number of iterations, utilize a for loop. Use a while loop when the condition depends on something that changes during execution. Use a do-while loop when the loop must run at least once.

2. Avoid Infinite Loops (Unless Intentional)

Always make sure your loop condition will eventually become false. Update the loop control variable properly to prevent accidental infinite loops.

3. Keep Loop Logic Simple

Don't stuff excess logic within a single loop. If the loop body becomes complex, break it into smaller functions for better readability and maintenance.

4. Avoid Repeating Calculations in the Loop Condition

If you're using a value that doesn't change during the loop, compute it once before the loop starts. This improves performance and readability.

5. Initialize Loop Variables Properly

Always assign a starting value to loop variables. Uninitialized variables can lead to unexpected behavior.

6. Use Descriptive Variable Names

While short names like i or j are fine for small loops, prefer meaningful names in larger or nested loops to improve code clarity.

7. Use break and continue Carefully

These statements can help control loop flow, but overusing them may make your code harder to follow. Use them only when it genuinely makes the code cleaner.

8. Avoid Off-by-One Errors

Carefully plan your loop boundaries. Check whether your loop should use <, <=, or other conditions to avoid skipping or repeating iterations.

Nested Loops in C

A loop nested inside another loop is known as a nested loop in C programming. This is beneficial for patterns, multi-dimensional arrays, and complicated logic structures because it enables you to repeat a set of instructions inside another repeated set.

Types of Nested Loops in C

You can nest any kind of loop (for, while, or do-while) inside each other. Here are the common types:

  1. Nested for loop inside for loop
  2. Nested while loop inside while loop
  3. Nested do-while loop inside do-while loop

Nested for Loop Inside Another for Loop in C

A nested for loop is when you place one for loop inside the body of another. It's commonly used to handle rows and columns, grids, patterns, or 2D arrays.

Syntax

for (initialization; condition; update) {
    for (initialization; condition; update) {
        // Inner loop code
    }
    // Code after inner loop
}

Example: Print a 4X4 Number Grid Program Using Nested for Loops

Below is a simple example provided to understand how nested for loops work.

#include <stdio.h>
int main() {
    for (int i = 1; i <= 4; i++) {          // Outer loop for rows
        for (int j = 1; j <= 4; j++) {      // Inner loop for columns
            printf("%d ", j);
        }
        printf("\n"); // Newline after each row
    }
    return 0;
}

Explanation

Output

1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

Nested while Loop Example in C

Nested while loops in C are loops placed inside another while loop, allowing repeated execution of inner code for each outer loop iteration commonly used for patterns, tables, and multi-dimensional data.

Syntax

while (condition1) {
    // Outer loop body

    while (condition2) {
        // Inner loop body
    }
}

Example Program to Print a 3x3 Star Grid Using Nested While Loops

#include <stdio.h>
int main() {
    int i = 1;
    while (i <= 3) {           // Outer loop for rows
        int j = 1;
        while (j <= 3) {       // Inner loop for columns
            printf("* ");
            j++;
        }
        printf("\n");          // Move to next line after each row
        i++;
    }
    return 0;
}

Explanation

Output

* * *
* * *
* * *

Nested do-while Loop Example

A nested do-while loop means placing one do-while loop inside another do-while loop. This allows you to perform a set of actions repeatedly within another repeated set of actions.

Syntax of Nested do-while Loop

do {
    // Outer loop body

    do {
        // Inner loop body
    } while (condition2);

} while (condition1);

Example Program to Print a 2x3 Grid of Stars Using Nested do-while Loops

Here is a simple program using nested do-while loops.

#include <stdio.h>
int main() {
    int i = 1;
    do {
        int j = 1;
        do {
            printf("* ");
            j++;
        } while (j <= 3); // Inner loop
        printf("\n");
        i++;
    } while (i <= 2); // Outer loop
    return 0;
}

Output

* * *
* * *

Loop Control Statements in C

Loop control statements in C modify the normal flow of loops. They provide additional control over how loops execute, allowing you to exit loops earlier, skip iterations, or jump to specific parts of your program. These statements are essential for writing efficient and flexible code.

In this section, you will explore the three main loop control statements in C:

  1. break Statement
  2. continue Statement
  3. goto Statement

1. break Statement

The break is the primary loop statement in C that terminates a loop immediately, regardless of its condition. When the break statement is encountered inside a loop, the loop is exited, and the program continues with the following statement after the loop.

When to use break?

Syntax of break

break;

Example: Using break in a Loop

#include <stdio.h>
int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break; // Exit the loop when i is 5
        }
        printf("%d ", i);
    }
    printf("\nLoop ended.\n");
    return 0;
}

Explanation

Output

1 2 3 4
Loop ended.

2. continue Statement

To go to the next iteration of a loop and bypass the current one, the continue statement is used. When the continue statement is encountered, the remaining code in the loop body is skipped, and the loop proceeds with the next iteration.

When to use continue?

Syntax of continue

continue;

Example: Using continue in a Loop

#include <stdio.h>
int main() {
    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            continue; // Skip the iteration when i is 3
        }
        printf("%d ", i);
    }
    printf("\nLoop ended.\n");
    return 0;
}

Explanation

Output

1 2 4 5
Loop ended.

3. goto Statement

The goto statement is used to jump to a specific part of the program, identified by a label. It allows you to transfer control to another part of the code, bypassing the normal flow of execution.

When to Use goto?

Syntax of goto

goto label;
...
label:

Example: Using goto in a Loop

#include <stdio.h>
int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i == 2 && j == 2) {
                goto end; // Jump to the label 'end'
            }
            printf("i = %d, j = %d\n", i, j);
        }
    }
end:
    printf("Loop ended.\n");
    return 0;
}

Explanation

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
Loop ended.

Key Differences Between break, continue, and goto

These three statements control the execution flow in loops and conditional statements, but serve different purposes.

Feature break continue goto
Purpose Exits the loop or switch statement immediately. Skips the current iteration and moves to the next iteration. Jumps to a labeled statement anywhere in the program.
Usage Used in loops (for, while, do-while) and switch statements. Used in loops (for, while, do-while). Used anywhere in the program with a label.
Effect on Loop Terminates the loop completely. Skips the rest of the current iteration and continues with the next cycle. Can move execution to any labeled part of the program.
Readability Improves clarity by allowing early exit from loops. Helps in skipping unwanted iterations cleanly. Reduces readability and maintainability, often leading to "spaghetti code."
Common Use Cases Exiting a loop when a condition is met (e.g., breaking out of a search loop when an item is found). Skipping specific cases in a loop (e.g., skipping even numbers in an iteration). Rarely recommended; used for error handling in legacy code.

Advantages of Loop Control Statements

In programming, loop control statements have special instructions that aid in controlling the way loops function. Here are a few of their main advantages:

1. Preventing Unnecessary Repetition

They allow you to break out of a loop early when certain conditions are satisfied, saving the program time by avoiding repetitive operations.

2. Handling Errors Simply

These statements can assist the program in reacting effectively to an unexpected event during a loop, such as skipping over bad data without crashing.

3. Enhancing Code Clarity

These statements make your code easier to read and understand by stating exactly when and how loops should stop or stages should be skipped.

4. Managing Resources Wisely

They help ensure that loops don't run longer than necessary, which is important for saving memory and processing power.

5. The Application of Complex Logic Simply

These statements offer an easy way of managing the flow, simplifying implementation for tasks requiring complex looping patterns.

Common Mistakes to Avoid for Loop Control Statements

When using loop control statements like goto, break, and continue, it's important to be aware of common pitfalls that can lead to difficulty reading, maintaining, or debugging code. Here are some mistakes to watch out for:

1. Overusing goto

Excessive use of goto can make code hard to follow and maintain. It's generally advisable to use structured control flow constructs instead.

2. Creating Infinite Loops

Failing to define proper termination conditions can result in loops that never end. Always ensure that loops have well-defined exit criteria to prevent endless execution.

3. Misusing continue

Using continue improperly can skip essential code within a loop iteration. Be cautious to ensure that important operations aren't inadvertently bypassed.

Practice Problems on Loops Asked in Companies

Here are three practice problems focusing on loops that are commonly encountered in technical interviews:

Problem 1: Sum of Digits

Problem Statement

Write a program that reads a positive integer and calculates the sum of its digits.

Input Format
Output Format

Solution

#include <stdio.h>

int main() {
    int n, sum = 0, remainder;

    // Prompt user for input
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    // Calculate sum of digits
    while (n != 0) {
        remainder = n % 10;  // Extract the last digit
        sum += remainder;    // Add it to the sum
        n /= 10;             // Remove the last digit
    }

    // Display the result
    printf("Sum of digits: %d\n", sum);

    return 0;
}

Explanation

The program repeatedly extracts the last digit of the number using the modulus operator (n % 10) and adds it to a running total (sum). It then removes the last digit by performing integer division by 10 (n /= 10). This process continues until all digits have been processed.

Sample Output

Enter a positive integer: 935
Sum of digits: 17

Problem 2: Reverse a Number

Problem Statement

Write a program that reads an integer and outputs its reverse.

Input Format
Output Format

Solution

#include <stdio.h>

int main() {
    int n, reversed = 0, remainder;

    // Prompt user for input
    printf("Enter an integer: ");
    scanf("%d", &n);

    // Reverse the number
    while (n != 0) {
        remainder = n % 10;               // Extract the last digit
        reversed = reversed * 10 + remainder; // Append it to the reversed number
        n /= 10;                          // Remove the last digit
    }

    // Display the result
    printf("Reversed number: %d\n", reversed);

    return 0;
}

Explanation

The program constructs the reversed number by extracting the last digit of the original number and appending it to the reversed number. This is achieved by multiplying the current reversed number by 10 and adding the extracted digit. The original number is then reduced by removing its last digit. This process repeats until the original number becomes zero.

Sample Output

Enter an integer: 12345
Reversed number: 54321

Problem 3: Fibonacci Sequence

Problem Statement

Write a program that prints the first n terms of the Fibonacci sequence.

Input Format
Output Format

Solution

#include <stdio.h>

int main() {
    int n, t1 = 0, t2 = 1, nextTerm;

    // Prompt user for input
    printf("Enter the number of terms: ");
    scanf("%d", &n);

    // Display the first two terms
    printf("Fibonacci Series: %d, %d", t1, t2);

    // Calculate and display the remaining terms
    for (int i = 3; i <= n; ++i) {
        nextTerm = t1 + t2;
        printf(", %d", nextTerm);
        t1 = t2;
        t2 = nextTerm;
    }
    printf("\n");

    return 0;
}

Explanation

The program initializes the first two terms of the Fibonacci sequence as 0 (t1) and 1 (t2). It then prints these two terms. For the subsequent terms, it calculates each new term by summing the previous two terms (nextTerm = t1 + t2), prints the new term, and updates the previous terms (t1 = t2; t2 = nextTerm). This loop continues until the desired number of terms is generated.

Sample Output

Enter the number of terms: 5
Fibonacci Series: 0, 1, 1, 2, 3

Conclusion

Loops and loop control statements are crucial components in C programming. They enable you to handle repetitive tasks more efficiently and manage the flow of your programs. You can write more efficient, readable, and flexible code by mastering the concept of loops in C programming and the loop control statements. These tools will support you in achieving your objectives, whether you are developing simple applications or intricate algorithms.

Therefore, when you need to repeat a section of code or manipulate the progression of your loops, consider the significance of loops in C and utilize them thoughtfully. With the information provided in this guide, you now understand loops and loop control statements in C, including their syntax and various applications. These principles will enhance your programming skills, whether coding a basic application or addressing complex algorithms.

Frequently Asked Questions

1. What are the 3 types of loops?

The three types of loops in C are:

  1. for loop (entry-controlled)
  2. while loop (entry-controlled)
  3. do-while loop (exit-controlled)

2. What are the three parts of a loop?

  1. Initialization – Sets up the loop control variable
  2. Condition – Checks if the loop should continue
  3. Update – Modifies the loop control variable

3. What are the 3 loop structures in C?

The three loop structures in C are:

  1. When a certain number of iterations is known, a for loop is utilized.
  2. When a certain number of iterations is uncertain, a while loop is utilized
  3. do-while loop ensures execution at least once before checking the condition

4. What is a finite loop?

A finite loop runs for a limited number of iterations and terminates when a predefined condition is met.

5. What is a fixed loop?

A fixed loop runs for a specific number of iterations, typically using a for loop with a predetermined number of repetitions.

6. What is the difference between while and do-while loops in C?

The key difference is that the while loop checks the condition before executing the loop body, whereas the do-while loop executes the loop body at least once before checking the condition.

7. How do you exit a loop in C?

You can exit a loop in C using the break statement, which immediately terminates the loop and moves to the next statement after it.

8. What is an infinite loop in C, and how can it be avoided?

An infinite loop never terminates because the loop condition never becomes false. It can be avoided by ensuring proper loop exit conditions, using break statements, or implementing correct loop updates.


Related Articles


Source: NxtWave - https://www.ccbp.in/blog/articles/loops-in-c