Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
Reading time: 20 minutes
A loop is used for executing a block of statements repeatedly until a given condition returns false. These loops save the programmer from writing long lines of codes performing the same task over and over again. C provides three kinds of loops:
- for loop
- while loop
- do-while loop
Parts of a loop
Loops consist of four major elements that govern the execution and working of a loop:
- Initialization Expression(s) The initialization of the control variable takes place under this.
- Test Expression The expression whose truth value decides whether the loop-body will get executed or not.
- In an entry-controlled loop the test expression is evaluated before entering into a loop.
- In an exit-controlled loop the test expression is evaluated before exiting from the loop.
-
Update Expression(s) These change the value of loop variable(s).
-
The Body of the loop The statements that are executed repeatedly form the body of the loop.
While loop
SYNTAX
while(condition){
//Statements to be executed repeatedly
// Increment (++) or Decrement (--) Operation
}
FLOW DIAGRAM
Order of execution
- The control variable is initialized.
- The test expression is evaluated
- If it evaluates to true, the loop enters the body
- And it is repeatedly executed, till the expression does not evaluate to false
- When the test expression evaluates to false, the loop is exited.
Example:
#include <stdio.h>
int main()
{
int i=0;
while(i<=2){
printf("Hello\n");
i=i+1;
}
printf("Out of loop");
}
Output:
Hello
Hello
Hello
Out of loop
while
Vs do while
loop
1. Syntax
Syntax of while loop as follows:
while(condition)
{
//statements;
}
Syntax of do while loop:
do
{
//statements;
} wile(condition);
2. Loop type
While loop is an entry controlled loop while do while loop is an exit controlled loop
3. Iterations
If condition is false, then no iteration take place in while loop but in case of do while loop, one iteration take place irrespective of the condition.
4. Example
Example of while loop:
int i=0,sum=0;
while(i<=10)
{
sum = sum + i;
i++;
}
Example of do while loop:
int i=0, sum=0;
do
{
sum = sum + i;
i++;
} while(i<=10);
Application
- Used when a condition needs to be fulfilled in order for a process to work.
- The condition needs to be checked before the process starts.
- Unlike a do-while loop, the body of the loop won't get executed until and unless the condition evaluates to true.