Loop Statement
Loop Statement
Loop Statement
Definition:
A loop is defined as a block of statements which are repeatedly executed for certain number of
times.
Terms used in loop:
loop variable
initialization
test condition
incrimination/decrimination
Loop variable: It is a variable used in the loop.
Initialization: It is the first step in which starting and final values is assigned to the loop
variable. Each time the updated value is checked by the loop itself.
Test condition: It is used to test the condition.
Incrimination/Decrimination: It is the numerical value added to or subtracted from the variable
in each round of the loop.
Two ways of loop control structures:
Entry
False
test con
True
Body of the
loop
Three types of loop control structures:
For loop
While loop
Do-while loop
For loop:
For loop allows to execute a set of instructions repeatedly until the certain becomes
false.
Assigning variable values, incrementation or decrementation and condition checking is
done in for statement only, where as other control structures are not offered all these
features in one statement.
Syntax:
Eg:
........
........
int i, sum=0, n ;
sum = sum + i;
........
........
Program: /* To find factorial for given number */
#include<stdio.h>
#include<conio.h>
main ( )
{
int n, fact=1,i;
clrscr ( );
printf ("enter the number for factorial=");
scanf ("%d", &n);
for (i=1; i<=n; i++)
{
fact = fact*i;
}
printf ("The factorial is=%d", fact);
getch();
}
Output:
Enter the number for factorial=5
The factorial is=120
Nested loops:
Eg:
........
........
int i, j;
printf (“/n”);
........
........
#include<stdio.h>
#include<conio.h>
main()
int n ,t, i, j;
clrscr ( );
t=0;
if((i % j)==0)
t=1;
break;
if (t==0)
getch ( );
Output:
1 2 3 5 7 11 13 17 19
While loop:
The while is an entry-controlled loop statement. The test-condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test-
condition is once again evaluated and if it is true, the body is executed once again. This process
of repeated execution of the body continues until the test-condition finally become false and the
control is transferred out of the loop. On exit, the program continues with the statement
immediately after the body of the loop.
Syntax:
while (test-condition)
{
body of the loop
}
Eg:
........
........
while ( i <= n)
i++;
........
........
Program: /* To find sum of individual digits */
#include<stdio.h>
#include<conio.h>
main()
int s,n=0,r;
clrscr();
scanf("%d",&s);
while(s!=0)
r=s%10;
n=n+r;
s=s/10;
getch();
Output:
Sum of digits=15
Do-while loop:
do
{
body of the loop
}
while (test-condition);
Eg:
........
........
do
i++;
while ( i<=5)
........
........
Program:
#include<stdio.h>
#include<conio.h>
main()
int a=0,b=1,c,s=0;
clrscr ( );
do
s=a+b;
a=b;
b=s;
s=a +b;
while (s<=c);
getch ( );
Output:
Enter a value 23
0 1 1 2 3 5 8 13 21
**********************