Looping Statement
Looping statements in C are used to repeatedly execute a block of code as long as a specified condition is true or for a fixed number of iterations. There are three main types of looping statements in C: the for loop, the while loop, and the do-while loop.
1. for loop
The for loop is used to execute a block of code for a specific number of iterations. It consists of an initialization expression, a condition expression, and an increment or decrement expression.
Syntax
for (initialization; condition; increment/decrement) {
// code to be executed in each iteration
}
Example
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
This for loop prints the numbers from 1 to 5.
2. while loop
The while loop repeatedly executes a block of code as long as a specified condition is true. The condition is evaluated before executing the loop body.
Syntax
while (condition) {
// code to be executed as long as the condition is true
}
Example
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
This while loop prints the numbers from 1 to 5, similar to the for loop in the previous example.
3. do-while loop
The do-while loop is similar to the while loop, but it executes the loop body at least once, and then continues to execute as long as the specified condition is true. The condition is evaluated after executing the loop body.
Syntax
do {
// code to be executed at least once
} while (condition);
Example
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
This do-while loop also prints the numbers from 1 to 5, but it guarantees that the loop body is executed at least once.
Looping statements provide a way to repeat a block of code, allowing for iteration and controlled execution of code. They are useful when you need to perform operations repeatedly or iterate over a collection of elements. The choice of which looping statement to use depends on the specific requirements of your program.