C Loops — For, While, Do-While, Break, Continue, and Goto
In this tutorial, you will learn about C Loops. We cover key concepts, practical examples, and best practices to help you master this topic.
C loops repeat code execution based on conditions. The for loop provides counter-controlled iteration, while loops check before executing, and do-while loops execute at least once.
Why It Matters
Repetition is fundamental to programming. Processing arrays, reading files, handling network connections, and implementing algorithms all require loops. Choosing the right loop type and understanding loop control mechanisms like break and continue directly affects code correctness and performance.
Real-World Use
Network servers use infinite loops with while(1) to accept connections indefinitely. File readers use while(fgets(...)) until EOF. Array processing typically uses for loops. Game engines use main loops running at 60 frames per second. Durga Antivirus Pro uses loops to scan every file in a directory tree.
What You Will Learn
- The for loop for known iteration counts
- The while loop for condition-based repetition
- The do-while loop for guaranteed execution
- Break, continue, and goto for loop control
- Infinite loops and nested loops
- Loop performance and optimization
Learning Path
flowchart LR A[Control Flow] --> B[Loops
You are here] B --> C[Arrays] C --> D[Strings] D --> E[Pointers] style B fill:#f90,color:#fff
The for Loop
The for loop is ideal when you know how many times to iterate:
#include <stdio.h>
int main() {
// Basic for loop
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
printf("\n");
// Output: 0 1 2 3 4
// Three parts: initializer; condition; increment
// All three are optional
// Decrementing
for (int i = 5; i > 0; i--) {
printf("%d ", i);
}
printf("\n");
// Output: 5 4 3 2 1
// Step by 2
for (int i = 0; i < 10; i += 2) {
printf("%d ", i);
}
printf("\n");
// Output: 0 2 4 6 8
return 0;
}
Expected output:
0 1 2 3 4
5 4 3 2 1
0 2 4 6 8
The for Loop Anatomy
for (initialization; condition; increment) {
// body
}
- Initialization runs once before the loop starts
- Condition is checked before each iteration. If false, the loop exits
- Body executes if the condition is true
- Increment runs after the body, then the condition is checked again
Multiple variables in initialization:
for (int i = 0, j = 10; i < j; i++, j--) {
printf("i=%d j=%d\n", i, j);
}
The while Loop
The while loop checks the condition before executing the body. If the condition is initially false, the body never executes:
#include <stdio.h>
int main() {
int count = 0;
while (count < 5) {
printf("%d ", count);
count++;
}
printf("\n");
// Output: 0 1 2 3 4
// Reading until sentinel value
int input;
printf("Enter numbers (negative to stop): ");
scanf("%d", &input);
while (input >= 0) {
printf("Got: %d\n", input * 2);
scanf("%d", &input);
}
return 0;
}
Why Use while Instead of for?
Use while when:
- The number of iterations is not known in advance
- The loop naturally reads "while condition is true, keep going"
- The iteration variable does not follow a simple increment pattern
The do-while Loop
The do-while loop executes the body at least once, then checks the condition:
#include <stdio.h>
int main() {
int x = 10;
do {
printf("x = %d\n", x);
x--;
} while (x > 5);
// Output: 10 9 8 7 6
// Executes even when condition is false initially
int y = 0;
do {
printf("This runs once.\n");
} while (y != 0);
return 0;
}
Expected output:
x = 10
x = 9
x = 8
x = 7
x = 6
This runs once.
When to Use do-while
The do-while is useful when you need to execute the body before checking the condition. Common examples include menu systems where you want to show the menu at least once, and reading user input with validation.
Break and Continue
break exits the loop immediately. continue skips the rest of the current iteration and moves to the next:
#include <stdio.h>
int main() {
// Break: exit loop early
printf("Break example: ");
for (int i = 0; i < 10; i++) {
if (i == 5) break;
printf("%d ", i);
}
printf("\n");
// Output: 0 1 2 3 4
// Continue: skip current iteration
printf("Continue example: ");
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue; // Skip even numbers
printf("%d ", i);
}
printf("\n");
// Output: 1 3 5 7 9
// Break in nested loops (only breaks inner loop)
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break;
printf("(%d,%d) ", i, j);
}
}
printf("\n");
// Output: (0,0) (1,0) (2,0)
return 0;
}
Expected output:
Break example: 0 1 2 3 4
Continue example: 1 3 5 7 9
(0,0) (1,0) (2,0)
The goto Statement
goto jumps to a labeled statement. It is rarely needed but has legitimate uses:
#include <stdio.h>
int main() {
// Error handling pattern with goto
int success = 0;
if (!phase_one()) {
goto cleanup;
}
if (!phase_two()) {
goto cleanup;
}
if (!phase_three()) {
goto cleanup;
}
success = 1;
printf("All phases completed.\n");
cleanup:
if (!success) {
printf("Operation failed, cleaning up.\n");
}
return 0;
}
int phase_one() { return 1; }
int phase_two() { return 0; } // Fails here
int phase_three() { return 1; }
Expected output: Operation failed, cleaning up.
goto Guidelines
Use goto only for:
- Breaking out of deeply nested loops
- Centralized error handling and cleanup
- The Linux kernel uses goto extensively for this pattern
Never use goto to jump backward (creating a loop) or to jump into the middle of a block.
Infinite Loops
Sometimes you want a loop that never ends:
#include <stdio.h>
#include <stdbool.h>
int main() {
int counter = 0;
// Common ways to create infinite loops
// while (1) { ... }
// for (;;) { ... }
while (1) {
printf("Iteration %d\n", counter);
counter++;
if (counter >= 5) {
break; // Exit the infinite loop
}
}
return 0;
}
Expected output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Infinite loops are common in Embedded Systems (main program loop), servers (accepting connections), and event-driven programs.
Nested Loops
Loops can contain other loops. The inner loop completes all its iterations for each iteration of the outer loop:
#include <stdio.h>
int main() {
// Multiplication table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%3d ", i * j);
}
printf("\n");
}
return 0;
}
Expected output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Loop Comparison
| Loop Type | When to Use |
|---|---|
for |
Known number of iterations |
while |
Unknown count, check before each iteration |
do-while |
Must execute at least once |
Infinite while(1) |
Servers, event loops |
for(;;) |
Alternative infinite loop syntax |
Common Mistakes
1. Off-by-One Errors
for (int i = 0; i <= 5; i++) // 6 iterations: 0,1,2,3,4,5
for (int i = 0; i < 5; i++) // 5 iterations: 0,1,2,3,4
Use < for zero-based indexing and <= for inclusive ranges.
2. Infinite Loop by Accident
for (int i = 0; i < 10; i++) // Wrong: no increment
The loop variable must be modified to eventually make the condition false.
3. Modifying the Loop Variable Inside the Body
for (int i = 0; i < 10; i++) {
i += 2; // Skip ahead -- usually a bug
}
Modifying the loop variable can lead to unexpected behavior. Use continue instead.
4. Comparing Floating-Point Values in Loop Conditions
for (double x = 0.0; x != 1.0; x += 0.1) // May never exit!
Floating-point rounding errors mean the condition may never be exactly true.
5. Using Semicolons After for or while
for (int i = 0; i < 10; i++); // Empty loop body!
{
printf("This runs once.\n");
}
A semicolon immediately after a loop control creates an empty body.
Practice Questions
What is the difference between while and do-while? while checks the condition before executing the body. do-while executes the body once, then checks.
How many times does
for (int i = 0; i < 5; i++)iterate? 5 times: i = 0, 1, 2, 3, 4.What does break do in a loop? It immediately exits the loop, continuing with the next statement after the loop.
What does continue do in a loop? It skips the rest of the current iteration and moves to the next iteration.
Challenge: Write a program that prints a diamond pattern using nested loops.
Mini Project: Prime Number Finder
#include <stdio.h>
#include <stdbool.h>
int main() {
int limit = 50;
printf("Prime numbers up to %d: ", limit);
for (int num = 2; num <= limit; num++) {
bool is_prime = true;
for (int divisor = 2; divisor * divisor <= num; divisor++) {
if (num % divisor == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
printf("%d ", num);
}
}
printf("\n");
return 0;
}
Expected output: Prime numbers up to 50: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
FAQ
What is Next
Now that you understand loops, proceed to Arrays in C to learn how to store and manipulate collections of data using arrays.