C Loops

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

Programming languages provide various control structures that allow more complex execution paths.

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

循环结构

Loop Types

The C language provides the following types of loops. Click the link to view details of each type.

Loop TypesDescription
while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the body of the loop.
for LoopExecutes a sequence of statements multiple times, simplifying the code that manages the loop variable.
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 any while, for, or do..while loop.

More:Difference between C while and do while


Loop Control Statements

Loop control statements change the execution order of your code. With them, you can achieve jumps in code.

C provides the following loop control statements. Click the link to view details of each statement.

Control StatementsDescription
break StatementTerminateLoopsorswitchstatement, the program flow will continue to execute the next statement immediately following the loop or switch.
continue StatementTells a loop body to immediately stop the current loop iteration and begin the next loop iteration.
goto StatementTransfers control to a labeled statement. However, it is not recommended to use the goto statement in programs.

Infinite Loop

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

Example

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

When the condition expression is absent, it is assumed to be true. You can also set an initial value and an increment expression, but in general, C programmers tend to use the for(;;) construct to represent an infinite loop.

Note:You can pressCtrl + CA key terminates an infinite loop.

other extensions