Loops in C:
In C, loops are used to execute a set of statements repeatedly until the given condition is satisfied.
In loops sequence of statements to be executed inside the curly braces (“{}”) is known as the loop body. Every execution of the loop body condition is checked and if the condition is true loop body executes again. When condition checked to be False then loop body will not to be executed and come out of the loop and execute the remaining part of the program.
Types of the Loops in C language:
There are three types of loops in C language. They are:
1) while loop.
1) while loop.
2) do-while loop.
3) for loop.
Read: C For loop
Syntax of While loop:
While Loop syntax:
while(condition)
{
//body of the loop (statements)//
//body of the loop (statements)//
}
Explanation of the above diagram: In the while loop, the first condition is checked. If the condition is True, the code inside the body (means inside the parenthesis) will be executed. Again the loop executes until the condition becomes False when the condition becomes false exists from while loop.
Example of while program:
C While loop program:
#include<stdio.h>
void main()
{
{
int i = 1;
while( i < 5)
{
printf("i = %d\n",i);
i++;
}
}
Output:
i = 1
i = 2
i = 3
i = 4
Explanation:
1) The first variable of type integer is declared and initialized to “1”.
2) While the loop condition is checked ( 1 < 5) condition is true. So the value of “i” is printed.
3) Then the value is incremented (i++) it becomes i = 2. If we did not use any increment (or) decrement operator then while loop will be executed continuously with a value i = 1. So we used the increment operator to satisfy the condition.
4) The cycle continues until “i” becomes “5”. When “i” becomes “5” the condition becomes fails. Control jumps out of the while loop.
Do-while: The do-while loop first executes the body of the loop and then the condition statement executes. If the expression is true, the loop repeat or else the loop terminates. There is a semicolon at the end of while() in do.
Syntax of Do - while loop:
C Do- While loop Syntax:
do
{
//body of the loop//
//body of the loop//
}
while(condition);
Example of Do-while program:
C Do- While loop program:
#include<stdio.h>
void main()
{
int i = 1;
do
{
printf("i = %d\n",i);
i++;
}
while( i < 5);
}
Output:
i = 1
i = 2
i = 3
i = 4