Loops in C - while, for and do while loop

Loops in C programming, including while, for, and do-while, are control structures that allow you to repeatedly execute a block of code as long as a specific condition is met or for a specified number of iterations.

while Loop

The while loop repeatedly executes a block of code as long as a specified condition remains true.

Syntax:
while (condition) { // Code to execute }

The condition is evaluated first. If the condition is true, the block of statements is executed. The block of statements is then executed again, and the condition is evaluated again. This process continues until the condition is false.

Example: Printing numbers from 1 to 5 using a while loop:
int i = 1; while (i <= 5) { printf("%d ", i); i++; }

for Loop

The for loop is used when you know the number of iterations in advance. It consists of three parts: initialization, condition, and increment.

Syntax:
for (initialization; condition; increment) { // Code to execute }

The initialization statement is executed once before the loop starts. The condition is evaluated before each iteration of the loop. If the condition is true, the block of statements is executed. The increment statement is executed after each iteration of the loop.

Example: Printing numbers from 1 to 5 using a for loop:
for (int i = 1; i <= 5; i++) { printf("%d ", i); }

do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will execute at least once because the condition is checked after the loop body.

Syntax:
do { // Code to execute } while (condition);

The block of statements is executed first. The condition is evaluated after the block of statements is executed. This means that the block of statements is guaranteed to be executed at least once, even if the condition is false.

Example: Receiving user input until a valid value is entered using a do-while loop:
int num; do { printf("Enter a positive number: "); scanf("%d", &num); } while (num <= 0);

Conclusion

Loop structures are essential for automating repetitive tasks, iterating over data, and creating efficient and dynamic programs. The choice of which loop to use depends on the specific requirements of your program, such as the number of iterations and the condition to be met.