C loop


Sometimes, we may need to execute the same block of code multiple times. Normally, statements are executed sequentially: the first statement in the function is executed first, followed by the second statement, and so on.

Programming languages ​​provide a variety of control structures for more complex execution paths.

Loop statements allow us to execute a statement or statement group multiple times. The following is a flow chart of loop statements in most programming languages:

1055.png

Loop type

C language provides the following loop types. Click on the links to view details on each type.

Loop typeDescription
while loopWhen the given condition is true When, a statement or group of statements is repeated. It tests the condition before executing the loop body.
for loopExecute a sequence of statements multiple times to simplify the code for managing loop variables.
do...while loopIt is similar to the while statement except that it tests the condition at the end of the loop body.
Nested LoopsYou can use one or more loops inside a while, for, or do..while loop.

Loop control statements

Loop control statements change the execution order of your code. Through it you can achieve code jumps.

C provides the following loop control statements. Click on the links to see the details of each statement.

Control statementDescription
break statementTerminationLoop or switch statement, the program flow will continue to execute the next statement immediately following the loop or switch.
continue statement tells a loop body to immediately stop this loop iteration and restart the next loop iteration.
goto statement Transfers control to the marked statement. However, it is not recommended to use goto statements in programs.

Infinite Loop

If the condition never becomes false, the loop will become an infinite loop. for Loops in the traditional sense can be used to implement infinite loops. Since none of the three expressions that make up the loop are required, you can leave some of the conditional expressions blank to form an infinite loop.

#include <stdio.h> int main (){   for( ; ; )   {
      printf("This loop will run forever.\n");   }   return 0;}

When the conditional expression does not exist, it is assumed to be true. You can also set an initial value and increment expressions, but generally, C programmers prefer to use the for(;;) construct to represent an infinite loop.

Note: You can terminate an infinite loop by pressing Ctrl + C.