for / while / do-while
| Since: | C89(1989) |
|---|
Loop constructs used to repeat the same process. Use for when the number of iterations is known, while to repeat as long as a condition holds, and do while when you need the body to execute at least once.
Syntax
for (initialization; condition; update) {
process;
}
// Repeats while the condition is true (condition is evaluated first).
while (condition) {
process;
}
// Executes the body first, then evaluates the condition (runs at least once).
do {
process;
} while (condition);
// Exits the loop immediately.
break;
// Skips the rest of the current iteration and moves to the next.
continue;
Loop Control Keywords
| Keyword | Description |
|---|---|
| for | Writes initialization, condition, and update in a single line. Best suited when the number of iterations is known. |
| while | Repeats the body while the condition is true. If the condition is false from the start, the body never executes. |
| do while | Executes the body first, then checks the condition. The body always runs at least once. |
| break | Immediately exits the current loop or switch statement. |
| continue | Skips the remaining statements in the current iteration and proceeds to the next one. |
Sample Code
sample_for_while.c
#include <stdio.h>
int main(void) {
// Use a for loop to print 1 through 5.
for (int i = 1; i <= 5; i++) {
printf("%d ", i); // Outputs "1 2 3 4 5 ".
}
printf("\n");
// Use nested for loops to print part of a multiplication table.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d*%d=%d ", i, j, i * j);
}
printf("\n");
}
// Use a while loop to repeat while the condition holds.
int n = 1;
while (n <= 100) {
n *= 2;
}
printf("First power of 2 greater than 100: %d\n", n); // Outputs "128".
// Use do while to execute at least once.
int count = 0;
do {
count++;
printf("count = %d\n", count);
} while (count < 3); // Prints 3 times.
// Use break to exit the loop once the target element is found.
int nums[] = {3, 7, 2, 9, 4};
for (int i = 0; i < 5; i++) {
if (nums[i] == 9) {
printf("9 is at index %d.\n", i); // Outputs "9 is at index 3.".
break;
}
}
// Use continue to print only even numbers.
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) continue; // Skip odd numbers.
printf("%d ", i); // Outputs "2 4 6 8 10 ".
}
printf("\n");
return 0;
}
Run the following command:
gcc for_while.c -o for_while ./for_while 1 2 3 4 5 1*1=1 1*2=2 1*3=3 2*1=2 2*2=4 2*3=6 3*1=3 3*2=6 3*3=9 First power of 2 greater than 100: 128 count = 1 count = 2 count = 3 9 is at index 3. 2 4 6 8 10
Common Mistakes
Common Mistake: Off-by-One Error
When the loop termination condition does not match the number of array elements, out-of-bounds access occurs.
#include <stdio.h>
int main(void) {
int arr[5] = {10, 20, 30, 40, 50};
/* NG: i <= 5 goes out of bounds (arr[5] does not exist) */
for (int i = 0; i <= 5; i++) {
printf("%d\n", arr[i]);
}
return 0;
}
arr[5] is out of bounds, producing an indeterminate value or a crash.
loop_oob_ok.c
#include <stdio.h>
int main(void) {
int arr[5] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
/* OK: use < n */
for (int i = 0; i < n; i++) {
printf("%d\n", arr[i]);
}
return 0;
}
Run the following command:
gcc loop_oob_ok.c -o loop_oob_ok ./loop_oob_ok 10 20 30 40 50
Notes
Since C99, you can declare the loop counter directly in the initialization part of a for statement (e.g., for (int i = 0; ...)). In this case, the variable's scope is limited to the loop body.
An incorrect loop termination condition can cause an infinite loop. Accessing beyond the array size results in undefined behavior. Use sizeof to check array sizes.
while (1) and for (;;) are idiomatic ways to write an intentional infinite loop, commonly used in event loops or server loops in combination with break. For combining loops with conditionals, see if / else.
If you find any errors or copyright issues, please contact us.