C Loops
Loops are one of the fundamental control structures in programming. They allow you to execute a block of code repeatedly, making them essential for tasks like processing collections of data, implementing repetitive calculations, or continuing operations until a certain condition is met.
C provides three primary loop structures: for
, while
, and do-while
. Each has its own use cases and syntax, though they can often be used interchangeably.
The for
Loop
The for
loop is typically used when the number of iterations is known or predictable. It provides a compact way to initialize, check, and update variables in a single line.
Syntax
for (initialization; condition; update) {
// Code to be executed
}
- Initialization: Executed once at the beginning of the loop
- Condition: Checked before each iteration; the loop continues as long as it's true
- Update: Executed at the end of each iteration, generally to modify the control variable
Example
#include <stdio.h>
int main() {
// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
// Output: 1 2 3 4 5
return 0;
}
You can omit any part of the for
loop syntax by using semicolons as placeholders. For example, for(;;)
creates an infinite loop.
The while
Loop
The while
loop is used when the number of iterations is not known in advance, and the loop should continue as long as a specified condition is true.
Syntax
while (condition) {
// Code to be executed
}
The condition is evaluated before each iteration. If it's true, the code inside the loop executes; otherwise, the loop terminates.
Example
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
// Output: 1 2 3 4 5
return 0;
}
The do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code inside the loop executes at least once, as the condition is checked after the first execution.
Syntax
do {
// Code to be executed
} while (condition);
Example
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
// Output: 1 2 3 4 5
return 0;
}
Remember to include the semicolon after the closing parenthesis in a do-while
loop.
Nested Loops
You can place a loop inside another loop, creating what's called a nested loop. This is useful for working with multi-dimensional data structures or generating complex patterns.
Example
#include <stdio.h>
int main() {
// Print a simple 3x3 pattern
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("(%d,%d) ", i, j);
}
printf("\n");
}
return 0;
}
Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
Infinite Loops
An infinite loop runs indefinitely unless explicitly broken. While usually a programming error, infinite loops can be useful in scenarios like event listeners or daemon processes.
Examples
// Infinite for loop
for (;;) {
// Will run forever unless break is used
}
// Infinite while loop
while (1) {
// Will run forever unless break is used
}
// Infinite do-while loop
do {
// Will run forever unless break is used
} while (1);
Be careful with infinite loops! They can freeze your program or consume all available CPU resources. Always ensure there's a way to exit the loop, like a break
statement triggered by some condition.
Loop Control Statements
While loops naturally terminate when their condition becomes false, you can also control their execution with:
break
: Exits the loop immediatelycontinue
: Skips the current iteration and proceeds to the next onegoto
: Jumps to a labeled statement (use with caution)
We'll cover these in detail in the next section on Break & Continue statements.
Which Loop to Choose?
- Use a for loop when you know the number of iterations in advance
- Use a while loop when you want to continue until a condition becomes false
- Use a do-while loop when you need to execute a block at least once
Practice Exercises
- Write a program to print all even numbers from 2 to 20 using each type of loop.
- Create a program that calculates the factorial of a number using a loop.
- Write a program that prints the multiplication table (1 to 10) of a given number.
- Implement a program that reverses a number using a loop (e.g., 1234 becomes 4321).
By mastering loops in C, you gain the ability to automate repetitive tasks and process data efficiently. In the next section, we'll explore how to control loop execution more precisely using break and continue statements.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)