- while loop (or) while statement :
The while loop is an entry control loop. In this, first
condition is checked and if it true then body of the loop is executed, It will
execute again and again till the condition is false. The syntax is:
while(condition)
{
body of the loop(statements);
}
statements;
Ex:/*program for reverse of a number */
#include<stdio.h>
#include<conio.h>
void main()
{
int r,n,rev=0;
clrscr();
printf(“Enter value of n:”);
scanf(“%d”,&n);
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
printf(“\nReverse is %d”,rev);
getch();
}
2.
do-while loop (or) do-while statement:
The
do-while loop is an exit control loop. In this, first body of the loop is
executed and then the condition is checked. If the condition is true, then the
body of the loop is executed. If the condition is false, then it will exit from
the loop.
The syntax for do-while loop is:
do
{
body of the loop(statements);
}while(condition);
statements;
Ex:/*program for reverse of a
number*/
#include<stdio.h>
#include<conio.h>
void main()
{
int r,n,rev=0;
clrscr();
printf(“Enter value of n:”);
scanf(“%d”,&n);
do
{
r=n%10;
rev=rev*10+r;
n=n/10;
}while(n>0);
printf(“\n reverse is %d” ,rev);
getch();
}
3.
for loop (or) for
statement :
for loop is an entry control
looping statement which repeats again and again till the condition is
satisfied.It is a one step loop, which ‘initialize’, ‘check the condition and
then ‘increment / decrement’.
The
syntax is :
for(initial
value; test condition; increment/decrement)
{
body of the loop(statements);
}
statements;
In the above for
loop, first the value is initialized, then in the loop the test condition is
checked and further the loop will increment/decrement according to the
requirement. After completion of the loop, i.e. when the condition becomes
false then the statement will be executed.
Ex:/*program to print 1 to 10
numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int I;
clrscr();
printf(“the numbers from 1 to 10 are:”);
for(i=1;i<=10;i++)
{
printf(“%d\n”,i);
}
getch();
}
Nested for:
When a for loop is executed
within another for loop then it is called nested for loop. In this first the
inner loop will be completed then the outer loop will be completed later
according to the condition. The syntax
is:
for(initial value-1; test condition-1;
increment-1/decrement-1)
{
for(initial value-2; test condition-2;
increment-2/decrement-2)
{
Inner body of
the loop(statements);
}
Outer body of the loop(statements);
}
Statements;
Ex:/*program to
illustrate nested for loop*/
#include<stdio.h>
#include<conio.h>
void main()
{
int I,j,n;
clrscr();
printf(“Enter value of n:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++);
{
printf(“%d”,j);
}
printf(“\n”);
}
getch();
}
Output: Enter value
of n 3
1
12
123
No comments:
Post a Comment