Loops in One Shot | C Programming | Lecture 3 | Complete C Course

Loops in C help you repeat a block of code multiple times without writing the same code again and again. This article explains different types of loops, including the 'for' loop in C, while loop in C, and other loop structures. By learning loops, you can write cleaner, faster, and more efficient programs.
authorImageVarun Saharawat23 Jun, 2026
Loops in One Shot | C Programming | Lecture 3 | Complete C Course

Writing the same statement many times can make your code long, messy, and difficult to manage. 

To solve it, programmers use iteration statements that automatically repeat code based on a condition. Learning loops in C helps you execute the same code multiple times with only a few lines, making programs shorter and easier to maintain.

What Are Loops in C?

A loop is a control flow statement that allows a block of code to run repeatedly until a specific condition becomes false. Instead of writing the same code many times, you place the code inside a loop, and the loop handles the repetition automatically. Loops help save time, reduce code length, and improve program readability.

Why Do We Need Loops in C?

Imagine you want to print a message three times. You could write three separate printf() statements. However, if you need to print the same message 1,000 times, writing 1,000 statements would be very difficult and inefficient. By using C loops, you can perform the same task with just a few lines of code, no matter how many times the action needs to repeat. This makes programming faster and more efficient.

What Are the Main Parts of Loops in C?

Every loop contains three important parts that control how it works and when it stops.

Initialization

Initialization sets the starting value of the loop control variable. This step runs only once before the loop starts. It tells the program where the loop should begin.

Test Condition

The test condition checks whether the loop should continue running. If the condition is true, the code inside the loop executes. If the condition becomes false, the loop stops. This condition helps control the number of times the loop runs.

Update Expression

The update expression changes the value of the loop control variable after each iteration. It usually increases or decreases the value. This step helps move the loop toward its stopping condition. Without an update expression, a loop may continue running forever and create an infinite loop.

Why Are Loops in C Important?

Loops are one of the most useful features in C programming.

They help programmers:

  • Reduce repeated code

  • Save development time

  • Improve code readability

  • Handle large amounts of data

  • Perform tasks automatically

  • Reduce programming errors

Classification of Loops in C

The C programming language classifies its loop statements based on where the test condition is evaluated. Understanding this difference ensures you choose the correct loop structure for your specific software requirements.

1. Entry Controlled Loops

In an entry-controlled structure, the program evaluates the test condition before allowing entry into the loop body. If the condition is false on the very first check, the internal code statements do not execute at all. The for loop in C and the while loop in C are prime examples of entry-controlled iteration statements.

2. Exit Controlled Loops

An exit-controlled structure checks its test condition at the absolute end of the loop body. This sequence ensures that the loop body executes at least once, regardless of whether the initial condition evaluates to true or false. The do-while loop is the only exit-controlled option available in C.

Examples of the Loops in C

The loop in C is an entry-controlled iteration statement best suited for situations where you know the exact number of iterations beforehand. It brings initialization, condition testing, and variable updating into a single line, making your source code clean and readable.

Syntax

C

for (initialization; test_condition; update_expression) {
    // Body of the loop to be executed repeatedly
}

Code Example: Printing Numbers 1 to 5

C

#include <stdio.h>

int main() {
    // A clean for loop to print numbers sequentially
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    return 0;
}

Output

Plaintext

1 2 3 4 5

  1. The loop starts by executing the initialization expression (int i = 1). This happens exactly once.

  2. The control checks the test condition (i <= 5). Since 1 is less than or equal to 5, the condition evaluates to true.

  3. The program enters the loop body and prints the value of i.

  4. After printing, the update expression (i++) increments the value of i to 2.

  5. Steps 2 through 4 repeat until i becomes 6, making the test condition false and terminating the loop.

The while loop in C is another entry-controlled structure, but it is typically used when the exact number of repetitions is not known before compilation. It evaluates a condition continuously and runs as long as that specific condition remains true.

Syntax

C

while (test_condition) {
    // Loop body statements
    // Update expression must be placed inside this body
}

Code Example: Printing Numbers 1 to 5

C

#include <stdio.h>

int main() {
    int i = 1; // Initialization happens outside
   
    while (i <= 5) {
        printf("%d ", i);
        i++; // Update expression inside the body
    }
    return 0;
}

Output

Plaintext

1 2 3 4 5

Key Differences in Control Flow

Unlike the loop in C, the while loop in C keeps its initialization entirely outside the loop header. If you forget to add the update expression inside the curly braces, the loop counter never changes, causing the application to execute endlessly.

The do-while loop is an exit-controlled loop that prioritises execution over testing. It executes the body statements first and evaluates the test condition at the bottom. This guarantees at least one full cycle of code execution, even if the condition is false from the start.

Syntax

C

do {
    // Loop body statements
    // Update expression
} while (test_condition);

Code Example: Verifying At-Least-Once Execution

C

#include <stdio.h>

int main() {
    int i = 10; // Condition is immediately false for i < 5
    do {
        printf("Value: %d\n", i);
        i++;
    } while (i < 5);
    return 0;
}

Output

Plaintext

Value: 10

As demonstrated by the output, even though 10 is not less than 5, the console prints the value once before terminating upon checking the bottom expression.

Different Iteration Statements of Loops in C

Choosing the wrong structural statement complicates your logic. This clear breakdown highlights the core operational behaviors of all three types of C loops:

Feature Details

The for Loop

The while Loop

The do-while Loop

Control Type

Entry Controlled

Entry Controlled

Exit Controlled

Condition Check

Top of the loop

Top of the loop

Bottom of the loop

Minimum Iterations

0 iterations

0 iterations

1 iteration

Best Scenario

Known number of cycles

Unknown number of cycles

Menu-driven programs

Syntax Focus

All expressions in one line

Only condition in header

Condition at the bottom

Loops in C Control Statements

Loop control statements alter the normal linear sequence of your loop iterations based on custom conditional branches. C provides three core keywords to manipulate loop behavior mid-cycle.

The break Statement

The break statement instantly terminates the active loop. Program execution jumps directly to the statement immediately following the loop body.

C

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        break; // Stops the loop entirely when i reaches 3
    }
    printf("%d ", i);
}
// Output: 1 2

The continue Statement

The continue statement skips the remaining code statements inside the loop body for the current cycle and shifts control immediately back to the next iteration check.

C

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue; // Skips printing 3 and moves to i = 4
    }
    printf("%d ", i);
}
// Output: 1 2 4 5

The goto Statement

The goto statement unconditionally transfers control to a specifically labeled statement in your function. It is generally avoided in structured programming because it makes code tracking complex.

Nested Loops in C and Matrix Patterns

Nesting means placing one loop entirely inside another loop's body. The inner iteration statement runs through its complete cycle for every single step executed by the outer loop. This is critical for reading multi-dimensional arrays or printing grid-like text patterns.

Code Example: Printing a Star Grid

C

#include <stdio.h>
int main() {
    int rows = 3;
    int cols = 4;
   
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("* ");
        }
        printf("\n"); // New line after outer step completes
    }
    return 0;
}

Output

Plaintext

* * * * * * * * * * * * ```
---
## Avoiding the Trap of Infinite Loops

An infinite loop occurs when the evaluated test expression never becomes false. As a result, the application gets locked in a perpetual execution cycle that drains computer system resources until forced to close.

### Infinite Structures in C
You can create infinite loops intentionally or accidentally using different syntax configurations:

Using a blank **for loop in C**:
```c
for ( ; ; ) {
    printf("Running forever...\n");
}

Using a fixed while loop in C:

C

while (1) {
    printf("Running forever...\n");
}

How to Fix Infinite Executions

  • Ensure your loop body contains an explicit update expression that modifies the control variable.

  • Double-check your boundary logical operators (like <, >, or !=) to guarantee they eventually fail.

  • Use a conditional break statement inside the block to exit when certain safety parameters are breached.

FAQs

What is the primary difference between a for loop and a while loop in C?

The primary difference lies in usage and layout. A for loop in C groups initialization, condition, and update expressions into one line, making it ideal when iteration counts are known. A while loop in C only holds the condition in its header, making it perfect when looping until an unknown event occurs.

Can an entry-controlled loop execute its body zero times?

Yes, entry-controlled C loops evaluate their conditions before executing any internal blocks. If the primary test expression is false when the program first reaches the loop, the entire body is skipped immediately.

What happens if I omit the condition in a for loop in C?

Omitting the test condition inside a for loop in C causes the compiler to automatically treat the missing expression as true. This forces the loop to run indefinitely unless stopped by an internal break command.

Is it possible to use multiple variables inside a single loop header?

Yes, C allows you to initialize and update multiple comma-separated variables inside a single loop header. However, you can only have one central logical test expression controlling the iteration statements.

Why does a do-while loop require a semicolon at the end?

Unlike entry-controlled structures, a do-while statement places its conditional check statement at the bottom. The trailing semicolon informs the compiler that the entire loop structure has officially concluded.
Popup Close ImagePopup Open Image
Talk to a counsellorHave doubts? Our support team will be happy to assist you!
Popup Image
avatar

Get Free Counselling Today

and Clear up all your Doubts

Talk to Our Counsellor just by filling out the form.
Student Name
Phone Number
IN
+91
OTP
Email Id
Join 15 Million students on the app today!
Point IconLive & recorded classes available at ease
Point IconDashboard for progress tracking
Point IconLakhs of practice questions
Download ButtonDownload Button
Banner Image
Banner Image