C Loop
At times, we may need to execute the same block of code multiple times. Normally, statements are executed sequentially: the first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
Loop statements allow us to execute a statement or group of statements multiple times. Below is the flowchart for loop statements in most programming languages:
Loop Types
C language provides the following types of loops. Click on the links to see details for each type.
Loop Type | 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 and abbreviates the code that manages the loop variable. |
do...while loop | Similar to a while statement, except that it tests the condition at the end of the loop body. |
nested loops | You can use one or more loops within any other while, for, or do..while loop. |
Loop Control Statements
Loop control statements change the execution sequence of your code. They allow you to jump from one part of the code to another.
C provides the following loop control statements. Click on the links to see details for each statement.
Control Statement | Description |
---|---|
break statement | Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. |
continue statement | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
goto statement | Transfers control to the labeled statement. However, it is not recommended to use the goto statement in your program. |
Infinite Loop
If the condition never becomes false, the loop will turn into an infinite loop. The for loop is traditionally used for this purpose. Since none of the three expressions that form the loop are required, you can make an endless loop by leaving the conditional expression empty.
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 increment expression, but in general, C programmers prefer to use the for(;;) construct to represent an infinite loop.
Note: You can terminate an infinite loop by pressing Ctrl + C
.