C: Loop Structures

🗓 Last updated: 2026-11-30👤 Written by: Harper✓ Reviewed by: Alex🏷 Category: C Tutorial

Loops are like running laps on a track -- keep going until you reach the finish line. When the condition is met, you stop. With loops, programs can do more than just run once.

Reference entries in this section: while for break continue switch goto

1. The while Loop

while is the most basic loop: it checks the condition first, executes the loop body if true, then checks again, repeating until the condition becomes false.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int count = 1;
    // While loop
    while (count <= 5) {
        // I/O operation
        printf("Lap %d\n", count);
        count++;
    }
    // I/O operation
    printf("Done!\n");
    // Return result
    return 0;
}
TEXT
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
Done!
⚠️ Note: The loop body must contain an operation that eventually makes the condition false (such as count++). Otherwise, you will get an infinite loop and the program will never stop.

(1) When to Use while

When the number of iterations is uncertain and depends on a runtime condition, while is the most natural choice. For example, reading input until a specific value:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int sum = 0;
    // Variable declaration
    int num = 0;
    // I/O operation
    printf("Enter positive integers to sum, 0 to finish: ");
    // I/O operation
    scanf("%d", &num);
    // While loop
    while (num != 0) {
        sum += num;
        // I/O operation
        scanf("%d", &num);
    }
    // I/O operation
    printf("Sum: %d\n", sum);
    // Return result
    return 0;
}
TEXT
Enter positive integers to sum, 0 to finish: 10 20 30 0
Sum: 60

2. The do-while Loop

do-while executes the loop body first, then checks the condition. This guarantees the loop body runs at least once, which is the key difference from while.

TEXT
#include <stdio.h>

int main(void) {
    int num;
    do {
        printf("Enter a number 1-10: ");
        scanf("%d", &num);
    } while (num < 1 || num > 10);
    printf("You entered: %d\n", num);
    return 0;
}
TEXT
Enter a number 1-10: 15
Enter a number 1-10: 0
Enter a number 1-10: 7
You entered: 7
⚠️ Note: The semicolon at the end of do-while must not be omitted: } while (condition); Forgetting the semicolon will cause a compile error.

(1) Choosing Between while and do-while


3. The for Loop

for combines initialization, condition checking, and updating into the header, making it the most commonly used loop form.

C
// For loop
for (initialization; condition; update) {
    loop body;
}
C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // For loop
    for (int i = 1; i <= 5; i++) {
        // I/O operation
        printf("%d ", i);
    }
    // I/O operation
    printf("\n");
    // Return result
    return 0;
}
TEXT
1 2 3 4 5

(1) for Loop Execution Flow

  1. Execute initialization (only once)
  2. Check condition -- if false, exit the loop
  3. Execute the loop body
  4. Execute the update
  5. Go back to step 2

(2) Flexibility of for

All three parts of for can be omitted, but the semicolons must remain:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int i = 1;
    // For loop
    for (; i <= 5; ) {
        // I/O operation
        printf("%d ", i);
        i++;
    }
    // I/O operation
    printf("\n");
    // Return result
    return 0;
}

Omitting the condition creates an infinite loop: for (;;) {} is equivalent to while (1) {}.

💡 Tip: Prefer for loops -- the loop variable, boundary condition, and update method are all visible at a glance, making it harder to accidentally write an infinite loop.

(3) Scope Considerations

C99 allows declaring variables in the for initialization. Such variables are scoped to the for loop only:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // For loop
    for (int i = 0; i < 3; i++) {
        // I/O operation
        printf("i = %d\n", i);
    }
    // Return result
    return 0;
}

After the loop ends, i is no longer accessible. If you need to use i outside the loop, declare it before the for.


4. Nested Loops

A loop inside another loop is a nested loop. Each iteration of the outer loop triggers a full run of the inner loop.

(1) Printing a Rectangle of Stars

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int rows = 3;
    // Variable declaration
    int cols = 5;
    // For loop
    for (int i = 0; i < rows; i++) {
        // For loop
        for (int j = 0; j < cols; j++) {
            // I/O operation
            printf("* ");
        }
        // I/O operation
        printf("\n");
    }
    // Return result
    return 0;
}
TEXT
* * * * *
* * * * *
* * * * *

(2) Multiplication Table

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // For loop
    for (int i = 1; i <= 9; i++) {
        // For loop
        for (int j = 1; j <= i; j++) {
            // I/O operation
            printf("%d*%d=%-4d", j, i, i * j);
        }
        // I/O operation
        printf("\n");
    }
    // Return result
    return 0;
}
TEXT
1*1=1
1*2=2   2*2=4
1*3=3   2*3=6   3*3=9
1*4=4   2*4=8   3*4=12  4*4=16
1*5=5   2*5=10  3*5=15  4*5=20  5*5=25
1*6=6   2*6=12  3*6=18  4*6=24  5*6=30  6*6=36
1*7=7   2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49
1*8=8   2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64
1*9=9   2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81
⚠️ Note: The total number of iterations in nested loops is the product of the outer and inner counts. Three levels of nesting can cause exponential growth -- be mindful of performance.


5. The break Statement

break immediately exits the current loop (only one level). The remaining iterations are skipped.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // For loop
    for (int i = 1; i <= 10; i++) {
        // Conditional check
        if (i == 5) {
// Break out of loop/switch
            // Break out of loop/switch
            // Break out of loop/switch
            // Break out of loop/switch
            break;
        }
        // I/O operation
        printf("%d ", i);
    }
    // I/O operation
    printf("\nStopped at 5\n");
    // Return result
    return 0;
}
TEXT
1 2 3 4
Stopped at 5

(1) Finding the First Element That Meets a Condition

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    int nums[] = {3, 7, 2, 9, 5, 1};
    // Variable declaration
    int target = 9;
    // Variable declaration
    int found = 0;
    // For loop
    for (int i = 0; i < 6; i++) {
        // Conditional check
        if (nums[i] == target) {
            // I/O operation
            printf("Found %d at index %d\n", target, i);
            found = 1;
// Break out of loop/switch
            // Break out of loop/switch
            // Break out of loop/switch
            // Break out of loop/switch
            break;
        }
    }
    // Conditional check
    if (!found) {
        // I/O operation
        printf("%d not found\n", target);
    }
    // Return result
    return 0;
}
TEXT
Found 9 at index 3

6. The continue Statement

continue skips the remaining statements in the current iteration and jumps to the next iteration (returning to the condition check or update step).

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // For loop
    for (int i = 1; i <= 10; i++) {
        // Conditional check
        if (i % 3 == 0) {
            // Skip this iteration
            continue;
        }
        // I/O operation
        printf("%d ", i);
    }
    // I/O operation
    printf("\nMultiples of 3 skipped\n");
    // Return result
    return 0;
}
TEXT
1 2 4 5 7 8 10
Multiples of 3 skipped
⚠️ Note: When using continue in while and do-while loops, make sure the update statement comes before continue, or you may create an infinite loop.


7. Common Loop Patterns

(1) Counting Pattern

Count how many elements satisfy a condition:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    int nums[] = {12, 45, 3, 67, 89, 23, 56};
    // Variable declaration
    int count = 0;
    // For loop
    for (int i = 0; i < 7; i++) {
        // Conditional check
        if (nums[i] > 50) {
            count++;
        }
    }
    // I/O operation
    printf("Numbers greater than 50: %d\n", count);
    // Return result
    return 0;
}
TEXT
Numbers greater than 50: 3

(2) Accumulation Pattern

Sum a series of values:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int sum = 0;
    // For loop
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    // I/O operation
    printf("Sum from 1 to 100: %d\n", sum);
    // Return result
    return 0;
}
TEXT
Sum from 1 to 100: 5050

(3) Search Pattern

Find the first element that meets a condition, then exit with break:

See the earlier break example.

(4) Traversal Pattern

Process each element in an array sequentially:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    int scores[] = {85, 92, 78, 96, 61};
    // Variable declaration
    int len = 5;
    // For loop
    for (int i = 0; i < len; i++) {
        // I/O operation
        printf("Student%d: %d %s\n", i + 1, scores[i], scores[i] >= 60 ? "Pass" : "Fail");
    }
    // Return result
    return 0;
}
TEXT
Student1: 85 Pass
Student2: 92 Pass
Student3: 78 Pass
Student4: 96 Pass
Student5: 61 Pass

8. Infinite Loops and How to Avoid Them

An infinite loop is one whose condition is always true. Intentional infinite loops use for(;;) or while(1), with break inside to exit:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int num;
    // While loop
    while (1) {
        // I/O operation
        printf("Enter a number (0 to quit): ");
        // I/O operation
        scanf("%d", &num);
        // Conditional check
        if (num == 0) {
// Break out of loop/switch
            // Break out of loop/switch
            // Break out of loop/switch
            // Break out of loop/switch
            break;
        }
        // I/O operation
        printf("You entered: %d\n", num);
    }
    // I/O operation
    printf("Goodbye!\n");
    // Return result
    return 0;
}

Unintentional infinite loops usually occur because the loop variable is never updated or is updated in the wrong direction:

TEXT
int i = 0;
while (i < 10) {
    printf("%d", i);
}
⚠️ Note: If your program seems to "freeze", the first thing to suspect is an infinite loop. Press Ctrl+C to force-terminate it.

▶ Example

Print a right triangle using nested loops:

▶ Try it Yourself
TEXT
*
* *
* * *
* * * *
* * * * *

▶ Example

Find the greatest common divisor of two positive integers using the Euclidean algorithm, demonstrating a while loop with an uncertain number of iterations:

▶ Try it Yourself
TEXT
GCD of 48 and 18 is 6

▶ Example 3: Password Input Loop

▶ Try it Yourself

输出(2 次太短后正确输入):

TEXT
Enter password (must be >= 6 chars): 123
Enter password (must be >= 6 chars): ab
Enter password (must be >= 6 chars): secret
Accepted on attempt 3: secret

9. Choosing Among the Three Loops

Situation Recommendation
Fixed number of iterations for
Must execute at least once do-while
Uncertain number of iterations while
Interactive menu do-while + switch
💡 Tip: All three loops can be logically converted to each other. Choose the one that best fits your use case.

Reference entries in this section: while for break continue switch goto

❓ FAQ

Q Should I use for or while?
A Use for when the number of iterations is known, and while when it is not. This is the most widely accepted guideline.
Q Can break exit multiple levels of loops?
A No. break only exits the innermost loop. To exit multiple levels, use a flag variable with an outer loop check, or goto (not recommended but sometimes practical).
Q Which is better: for(;;) or while(1)?
A They are functionally equivalent. while(1) is more readable; for(;;) is traditional C style. Choose based on your team's conventions.
Q Is it okay to use i, j, k as loop variables?
A In simple loops, this is a widely accepted convention. However, when the variable has business meaning (e.g., row, col, student_index), a descriptive name is better.

📖 Summary

📝 Exercises

  1. Write a program using a for loop to calculate the sum of factorials: 1! + 2! + 3! + ... + 10!.
  2. Write a program using nested loops to print an inverted right triangle (5 rows, 5 stars in row 1, 1 star in row 5).
  3. Write a program that reads a positive integer and prints its digits in reverse order (e.g., input 1234 outputs 4 3 2 1).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏