Loops: while, do-while and for
A loop repeats a block of statements while a condition holds. Thanks to loops, a ten-line program can process a million data items. C offers three forms: while, do-while and for. They are all equivalent in power, but each one expresses a different situation better, and choosing the right one makes the code more readable.
while: repeat while
while evaluates the condition before each turn; if it is false from the start, the body never runs. It is ideal when you do not know how many repetitions there will be, for example reading numbers until the user types 0. Always remember to change something inside the body that brings the condition closer to false, or you will have an infinite loop.
#include <stdio.h>
int main(void) {
int value;
int sum = 0;
int count = 0;
printf("Enter numbers (0 to finish):\n");
while (scanf("%d", &value) == 1 && value != 0) {
sum += value;
count++;
}
if (count > 0) {
printf("Sum: %d, average: %.2f\n", sum, (double)sum / count);
} else {
printf("No numbers entered.\n");
}
return 0;
}do-while: at least once
do-while checks the condition at the end, so the body runs at least once. It is perfect for validating input: you ask for the datum and repeat while it is invalid. Notice the mandatory semicolon after the final while.
#include <stdio.h>
int main(void) {
int age;
int ok;
do {
printf("Age (1-120): ");
ok = scanf("%d", &age);
if (ok != 1) {
int c;
while ((c = getchar()) != '\n' && c != EOF) {
}
if (c == EOF) {
return 1;
}
}
} while (ok != 1 || age < 1 || age > 120);
printf("Valid age: %d\n", age);
return 0;
}for: counting with control
for gathers initialization, condition and step in one line: for (int i = 0; i < n; i++). It is used when you know the number of repetitions or walk through a range. Declaring the variable inside the for (allowed since C99) limits its life to the loop. A classic is the off-by-one error: to repeat n times use i < n starting at 0, not i <= n. Loops can be nested, as when printing tables.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%4d", i * j);
}
printf("\n");
}
unsigned long long factorial = 1;
for (int n = 2; n <= 10; n++) {
factorial *= n;
}
printf("10! = %llu\n", factorial);
return 0;
}break and continue
break leaves the innermost loop immediately; continue jumps to the next cycle without finishing the current one. They are useful, but abusing them makes the flow hard to follow. In a for, continue still executes the step (i++); in a while you must make sure the control variable has already been updated before the continue, or the loop will never advance.
Common mistake: the loop that never ends or is off by one
The two classic loop errors are the infinite loop and the off-by-one error. The first happens when the condition never becomes false, for example while (x != 10) with x advancing by 3 (3, 6, 9, 12...) and skipping 10 without stopping. Always use an ordering comparison (x < 10) instead of equality. The second is repeating one time too many or too few: for (int i = 0; i <= n; i++) runs n + 1 times. For an array of n elements, the valid index goes up to n - 1. Before running, test the extremes in your head: what happens with n equal to 0 and with n equal to 1.
#include <stdio.h>
int main(void) {
int x = 0;
while (x < 10) { /* with != 10 and steps of 3 this would never stop */
x += 3;
}
printf("%d\n", x); /* 12 */
return 0;
}✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符