C Loops
Sometimes we may need to execute the same block of code multiple times. Normally, statements are executed sequentially: the first statement in a function executes first, followed by the second, and so on.
Programming languages provide various control structures for more complex execution paths.
Loop statements allow us to execute a statement or group of statements multiple times. The following is a flowchart of a loop statement in most programming languages:
Loop types
C provides the following types of loops. Click the links to see details of each type.
| Loop types | Description |
|---|---|
| while loop | Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
| for loop | Executes a sequence of statements multiple times, simplifying the code for managing loop variables. |
| do...while loop | Similar to the while statement except that it tests the condition at the end of the loop body. |
| Nested Loops | You can use one or more loops inside a while, for, or do..while loop. |
More information: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 the code.
C provides the following loop control statements. Click the links to see details of each statement.
| Control statement | Description |
|---|---|
| break statement | terminatesLoopor switch statement, program flow continues with the next statement immediately following the loop or switch. |
| continue statement | tells a loop body to immediately stop the current iteration and restart with the next iteration. |
| goto statement | Transfers control to a labeled statement. However, the use of the goto statement in programs is discouraged. |
Infinite loop
If the condition never becomes false, the loop becomes an infinite loop.for loops can be used to implement infinite loops in the traditional sense. Since none of the three expressions that make up the loop is required, you can leave some condition expressions empty to form an infinite loop.
Example
#include
<
stdio.h
int
main
(
)
{
for
(; ;
)
{
printf
(
"
This loop will run forever!
\
n
"
)
;
}
return
0
;
}
When the conditional expression is absent, it is assumed to be true. You can also set an initial value and an increment expression, but generally C programmers prefer the for(;;) construct to represent an infinite loop.
**Note:** You can press Ctrl + C to terminate an infinite loop.