Loop Structures

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.

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
#include <stdio.h>

int main(void) {
    int count = 1;
    while (count <= 5) {
        printf("Lap %d\n", count);
        count++;
    }
    printf("Done!\n");
    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.

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
#include <stdio.h>

int main(void) {
    int sum = 0;
    int num = 0;
    printf("Enter positive integers to sum, 0 to finish: ");
    scanf("%d", &num);
    while (num != 0) {
        sum += num;
        scanf("%d", &num);
    }
    printf("Sum: %d\n", sum);
    return 0;
}
TEXT
Enter positive integers to sum, 0 to finish: 10 20 30 0
Sum: 60

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.

C
#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.

Choosing Between while and do-while

The for Loop

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

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

int main(void) {
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}
TEXT
1 2 3 4 5

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

Flexibility of for

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

C
#include <stdio.h>

int main(void) {
    int i = 1;
    for (; i <= 5; ) {
        printf("%d ", i);
        i++;
    }
    printf("\n");
    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.

Scope Considerations

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

C
#include <stdio.h>

int main(void) {
    for (int i = 0; i < 3; i++) {
        printf("i = %d\n", i);
    }
    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.

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.

Printing a Rectangle of Stars

C
#include <stdio.h>

int main(void) {
    int rows = 3;
    int cols = 5;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
TEXT
* * * * *
* * * * *
* * * * *

Multiplication Table

C
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%d*%d=%-4d", j, i, i * j);
        }
        printf("\n");
    }
    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.

The break Statement

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

C
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break;
        }
        printf("%d ", i);
    }
    printf("\nStopped at 5\n");
    return 0;
}
TEXT
1 2 3 4
Stopped at 5

Finding the First Element That Meets a Condition

C
#include <stdio.h>

int main(void) {
    int nums[] = {3, 7, 2, 9, 5, 1};
    int target = 9;
    int found = 0;
    for (int i = 0; i < 6; i++) {
        if (nums[i] == target) {
            printf("Found %d at index %d\n", target, i);
            found = 1;
            break;
        }
    }
    if (!found) {
        printf("%d not found\n", target);
    }
    return 0;
}
TEXT
Found 9 at index 3

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
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i % 3 == 0) {
            continue;
        }
        printf("%d ", i);
    }
    printf("\nMultiples of 3 skipped\n");
    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.

Common Loop Patterns

Counting Pattern

Count how many elements satisfy a condition:

C
#include <stdio.h>

int main(void) {
    int nums[] = {12, 45, 3, 67, 89, 23, 56};
    int count = 0;
    for (int i = 0; i < 7; i++) {
        if (nums[i] > 50) {
            count++;
        }
    }
    printf("Numbers greater than 50: %d\n", count);
    return 0;
}
TEXT
Numbers greater than 50: 3

Accumulation Pattern

Sum a series of values:

C
#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    printf("Sum from 1 to 100: %d\n", sum);
    return 0;
}
TEXT
Sum from 1 to 100: 5050

Search Pattern

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

See the earlier break example.

Traversal Pattern

Process each element in an array sequentially:

C
#include <stdio.h>

int main(void) {
    int scores[] = {85, 92, 78, 96, 61};
    int len = 5;
    for (int i = 0; i < len; i++) {
        printf("Student%d: %d %s\n", i + 1, scores[i], scores[i] >= 60 ? "Pass" : "Fail");
    }
    return 0;
}
TEXT
Student1: 85 Pass
Student2: 92 Pass
Student3: 78 Pass
Student4: 96 Pass
Student5: 61 Pass

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
#include <stdio.h>

int main(void) {
    int num;
    while (1) {
        printf("Enter a number (0 to quit): ");
        scanf("%d", &num);
        if (num == 0) {
            break;
        }
        printf("You entered: %d\n", num);
    }
    printf("Goodbye!\n");
    return 0;
}

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

C
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:

C
#include <stdio.h>

int main(void) {
    int n = 5;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
▶ 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:

C
#include <stdio.h>

int main(void) {
    int a = 48, b = 18;
    int orig_a = a, orig_b = b;
    while (b != 0) {
        int temp = a % b;
        a = b;
        b = temp;
    }
    printf("GCD of %d and %d is %d\n", orig_a, orig_b, a);
    return 0;
}
▶ Try it Yourself
TEXT
GCD of 48 and 18 is 6

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.

❓ 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).
100%

🙏 帮我们做得更好

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

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