loop in c
Loops in c programming language, repeats statement, for a given number of times until given condition is satisfied.
c language has 2 types of loops
- Entry control loop
- Exit control loop
Entry control loop
Loops in which condition gets checked first, before executing the statements. Entry control loop are of two types
- for
- while
for loop
for loop is an entry control loop, which repeat statements until test condition become false.
Syntax
for(initialization; condition; iteration)
{
// statements;
}
initialization | The initial value from where the loop starts with. |
condition | It specifies the number of times loop will repeat itself. |
iteration | It either increases or decreases the loop cycle to continue. |
while loop
while loop is also an entry control loop, similar to for loop, but initialization is done outside loop and iteration is done inside loop body.
Syntax
initialization;
while(expression)
{
// statements
// iteration
}
Example
#include<stdio.h>
int i = 0;
while (i < 10)
{
printf("%d ", i);
i = i + 1;
}
Exit control loop
Loop in which statements executes first & test condition is checked later.
do-while loop
do while is an exit control loop, which executes statements first then check the test condition.
Syntax
do{
// statements
}while(expression)