Loops are a control flow construct in the C programming language that allow you to execute a block of code repeatedly, based on a given condition. There are three types of loops in C: for loops, while loops, and do-while loops.
The for loop is a control flow construct that allows you to execute a block of code repeatedly, with a specified number of iterations. The syntax for a for loop is as follows:
for (initialization; condition; increment/decrement) {
// code to execute
}
The initialization expression is executed once, before the loop starts. It is typically used to initialize a loop counter variable. The condition expression is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop is terminated. The increment/decrement expression is executed after each iteration of the loop. It is typically used to increment or decrement the loop counter variable.
For example, consider the following code:
int i;
for (i = 0; i < 10; i++) {
printf("%d ", i);
}
printf("\n");
In this example, the for loop iterates 10 times, from 0 to 9. The loop counter variable (i) is initialized to 0 before the loop starts, and is incremented by 1 after each iteration. The loop terminates when the value of i becomes 10 (i < 10 is false). The output of this code is “0 1 2 3 4 5 6 7 8 9”.
The while loop is a control flow construct that allows you to execute a block of code repeatedly, as long as a given condition is true. The syntax for a while loop is as follows:
while (condition) {
// code to execute
}
The condition expression is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop is terminated.
For example, consider the following code:
int i = 0;
while (i < 10) {
printf("%d ", i);
i++;
}
printf("\n");
In this example, the while loop iterates 10 times, from 0 to 9. The loop counter variable (i) is initialized to 0 before the loop starts, and is incremented by 1 after each iteration. The loop terminates when the value of i becomes 10 (i < 10 is false). The output of this code is “0 1 2 3 4 5 6 7 8 9”.
The do-while loop is a control flow construct that allows you to execute a block of code repeatedly, as long as a given condition is true. The syntax for a do-while loop is as follows:
do {
// code to execute
} while (condition);
The code inside the loop is executed once before the condition expression is evaluated. If the condition is true, the code inside the loop is executed again. If the condition is false, the loop is terminated.
For example, consider the following code:
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 10);
printf("\n");
In this example, the do-while loop iterates 10 times, from 0 to 9. The loop counter variable (i) is initialized to 0 before the loop starts, and is incremented by 1 after each iteration. The loop terminates when the value of i becomes 10 (i < 10 is false).