C: 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.
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.
// 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;
}
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
Done!
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:
// 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;
}
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.
#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;
}
Enter a number 1-10: 15
Enter a number 1-10: 0
Enter a number 1-10: 7
You entered: 7
do-while must not be omitted: } while (condition); Forgetting the semicolon will cause a compile error.
(1) Choosing Between while and do-while
- At least one execution needed ->
do-while(e.g., input validation) - Possibly zero executions ->
while(e.g., searching where nothing may be found)
3. The for Loop
for combines initialization, condition checking, and updating into the header, making it the most commonly used loop form.
// For loop
for (initialization; condition; update) {
loop body;
}
// 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;
}
1 2 3 4 5
(1) for Loop Execution Flow
- Execute initialization (only once)
- Check condition -- if false, exit the loop
- Execute the loop body
- Execute the update
- Go back to step 2
(2) Flexibility of for
All three parts of for can be omitted, but the semicolons must remain:
// 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) {}.
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:
// 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
// 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;
}
* * * * *
* * * * *
* * * * *
(2) Multiplication Table
// 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;
}
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
5. The break Statement
break immediately exits the current loop (only one level). The remaining iterations are skipped.
// 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;
}
1 2 3 4
Stopped at 5
(1) Finding the First Element That Meets a Condition
// 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;
}
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).
// 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;
}
1 2 4 5 7 8 10
Multiples of 3 skipped
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:
// 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;
}
Numbers greater than 50: 3
(2) Accumulation Pattern
Sum a series of values:
// 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;
}
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:
// 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;
}
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:
// 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:
int i = 0;
while (i < 10) {
printf("%d", i);
}
▶ Example
Print a right triangle using nested loops:
▶ Try it Yourself*
* *
* * *
* * * *
* * * * *
▶ Example
Find the greatest common divisor of two positive integers using the Euclidean algorithm, demonstrating a while loop with an uncertain number of iterations:
GCD of 48 and 18 is 6
▶ Example 3: Password Input Loop
▶ Try it Yourself输出(2 次太短后正确输入):
TEXTEnter 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 |
❓ FAQ
for or while?for when the number of iterations is known, and while when it is not. This is the most widely accepted guideline.break exit multiple levels of loops?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).for(;;) or while(1)?while(1) is more readable; for(;;) is traditional C style. Choose based on your team's conventions.i, j, k as loop variables?row, col, student_index), a descriptive name is better.📖 Summary
whilechecks before executing,do-whileexecutes before checking,forconcentrates all three elements in the headerforis the most commonly used loop structure for fixed-iteration loops- The total iteration count of nested loops equals the product of each level's count -- be mindful of performance
breakexits the current loop,continueskips the current iteration -- both only affect the innermost loop- Avoid unintentional infinite loops: ensure the loop variable is updated correctly and in the right direction
📝 Exercises
- Write a program using a
forloop to calculate the sum of factorials: 1! + 2! + 3! + ... + 10!. - Write a program using nested loops to print an inverted right triangle (5 rows, 5 stars in row 1, 1 star in row 5).
- Write a program that reads a positive integer and prints its digits in reverse order (e.g., input 1234 outputs 4 3 2 1).