Loops in C
Types of Loops in C
- while loop
- do-while loop
- for loop
- Nested loop
1. while loop:
The while statement is used to execute a single statement or block of statements repeatedly until the given condition is TRUE. It is also known as Entry control loop.
Syntax
control_variable_initialization;
while(condition)
{
statement(s);
control_variable_update;
}
2. do-while loop:
The do-while loop is similar to that of the while loop, but the main difference is while loop evaluates the condition first and then executes the statements, whereas the do-while loop executes the statements first before evaluating the condition. It is also known as Exit control loop.
Syntax
control_variable_initialization;
do
{
statement(s);
control_variable_update;
}
while(condition);
3. for loop:
It is a pre-tested loop and is used when the number of repetitions(iterations) is known. The syntax of for-loop consists of three parts: control variable initialization, condition, and control variable update. These three parts are separated by a semicolon(;).
Syntax
for(control_variable_initialization; condition; control_variable_update)
{
statement(s);
}
C program to find the sum of first 50 natural numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,sum=0;
for(i=1;i<=50;i++)
sum=sum+i; printf("The sum of first 50 natural numbers is %d", sum);
getch();
}
Output:
The sum of first 50 natural numbers is 1275
Note: Curly braces are optional if body of loop consists of single statement.
4. Nested loop:
A nested loop is a loop within a loop, an inner loop within the body of an outer one.
Syntax
for(initialization; condition; increment/decrement)
{
statement(s);
for(initialization; condition; increment/decrement)
{
statement(s);
...........
}
...........
}