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.
#include <stdio.h>
int main(void) {
int count = 1;
while (count <= 5) {
printf("Lap %d\n", count);
count++;
}
printf("Done!\n");
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.
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:
#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;
}
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.
#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.
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)
The for Loop
for combines initialization, condition checking, and updating into the header, making it the most commonly used loop form.
for (initialization; condition; update) {
loop body;
}
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
1 2 3 4 5
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
Flexibility of for
All three parts of for can be omitted, but the semicolons must remain:
#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) {}.
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:
#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
#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;
}
* * * * *
* * * * *
* * * * *
Multiplication Table
#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;
}
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
The break Statement
break immediately exits the current loop (only one level). The remaining iterations are skipped.
#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;
}
1 2 3 4
Stopped at 5
Finding the First Element That Meets a Condition
#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;
}
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).
#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;
}
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.
Common Loop Patterns
Counting Pattern
Count how many elements satisfy a condition:
#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;
}
Numbers greater than 50: 3
Accumulation Pattern
Sum a series of values:
#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;
}
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:
#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;
}
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:
#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:
int i = 0;
while (i < 10) {
printf("%d", i);
}
Example
Print a right triangle using nested loops:
#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;
}
*
* *
* * *
* * * *
* * * * *
Example
Find the greatest common divisor of two positive integers using the Euclidean algorithm, demonstrating a while loop with an uncertain number of iterations:
#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;
}
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 |
❓ 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).



