Loops are used to execute a block of statements in repetition until a specific condition is satisfied.
There are 3 types of loops in C:
1. for loop
2. while loop
3. do while loop
1. for Loop:
Syntax for for loop:
for(initialization statement; test expression; increment/ decrement)
{
code to be executed
}
The initialization statement executes only one time at the beginning of the loop. Then the test condition is checked. The loop terminates if the test condition is False. If the condition is True, the block of statements inside the body of for loop is executed and updated expression is updated. This process continues till the expression is False.
Program to find the sum of first n natural numbers where n is entered by the user.
#include<stdio.h>
#include<conio.h>
void main()
{
int num, i, sum = 0;
printf(Enter value for num);
scanf(%d, & num );
for(i = 0; i < num; i++)
{
sum = sum+ i;
}
printf(Sum is:, sum);
return 0;
}
Output
Enter value for num
15
Sum is: 120
2. While Loop
Syntax of While loop:
while(condition)
{
statement;
}
While loop tests the condition before executing the body of the loop. It repeats the block of code while given condition is true.
Program to print first 20 natural numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf(Enter value for num);
scanf(%d, & num );
while(num<= 20)
{
printf(%d\t, num);
num++;
}
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
3. do while Loop
Syntax for do while loop:
do
{
statement;
}
while(condition)
do while is an exit control loop. do statement first executes the body of loop and at the end the condition is checked using while statement.
Program to print numbers from 10 that are less than 20.
#include<stdio.h>
int main()
{
int n = 10;
do
{
printf(Value of n: %d\n, n);
n = n+1;
}
while(n<20);
return 0;
}
Output:
Value of n: 10
Value of n: 11
Value of n: 12
Value of n: 13
Value of n: 14
Value of n: 15
Value of n: 16
Value of n: 17
Value of n: 18
Value of n: 19
0 Comment(s)