After decision-making statements there comes the loops in C languages. In a loop, a block of code is executed sequentially a number of times mentioned in the statement. For example, the first statement will execute first, then second, and so on.
There are the following types of loops in the C language. Let's know in brief about them.
Sr.No. |
Loop Type & Description |
|
While loop continuously repeats statements while a given condition is true and tests the condition before executing the loop body. |
|
For loop executes a sequence of statements multiple times and follows the code that manages the loop variable. |
|
It is quite similar to a while statement, except that it checks the condition at the end of the loop body. |
|
You can use one or more than one loop inside any other while, for, or do-while loop. |
The loop in C becomes an infinite loop when a condition never becomes false. By making a condition null you can easily make an infinite loop
We can terminate an infinite loop by pressing Ctrl + C keys.
for loop example
#include <stdio.h> int main () { int a; /* for loop execution */ for( a = 1; a < 10; a = a + 1 ){ printf("value of a: %d\n", a); } return 0; } |
The above loop will execute until the value of a reaches to 9. When it increment to 10 then the condition will not saticifies and breaks the loop.
Output
value of a: 1 value of a: 2 value of a: 3 value of a: 4 value of a: 5 value of a: 6 value of a: 7 value of a: 8 value of a: 9 |
Loop Controll Statements
This Loop controll statements will breaks the current loop and finish the current executed function.
C Language has below controll statments
break controll example
#include <stdio.h> int main () { /* local variable definition */ int a = 1; /* while loop execution */ while( a < 10 ) { printf("value of a: %d\n", a); a++; if( a > 5) { /* terminate the loop using break statement */ break; } } return -1; } |
The above while loop will executes until the value of a increments to 5. when it reached 5 the break controll statement will stop the current loop
output
value of a: 1 value of a: 2 value of a: 3 value of a: 4 value of a: 5