Looping is a repetitive structure.In looping a group of structures are executed until some condition has been satisfied.
In C following loop structure are available:
- for loop
- while loop
- do-while loop
Syntax:
for ( initialisation expressions;
test expression;
update expression;)
body-of-the-loop;
test expression;
update expression;)
body-of-the-loop;
Example:
int i; //declare variable
for(i=1;i<=10;i++)
printf("\n%d",i);
getch();
for(i=1;i<=10;i++)
printf("\n%d",i);
getch();
Note:
case 1.:
for(initialise exp1 initialise exp2;
test expression 1 test expression 2;
update expression 1 update expression 2)
test expression 1 test expression 2;
update expression 1 update expression 2)
case 2.:
for( ;test expression;update expression)
case 3.:
for(initialise exp; ;update expression)--infinite
for( ; ;)--infinite
for( ; ;)--infinite
case 4.:
for(initialise exp;test expression;update expression); -empty no body
case 5.:
for(int i=1;i<10;i++) --deceleration of i
while loop is an entry control loop. In a while loop control variable should be initialised before the loop begins as an uninitialised variable can not be used in an expression.The loop variable should be updated inside the body of the while.
Syntax:
while(expression)
loop-body
loop-body
Example:
int i=0;
while(i<=10)
{
printf("%d",i);
i++;
}
while(i<=10)
{
printf("%d",i);
i++;
}
Note:
repeat expression.
syntax: while (boolean) statement 1;
example while(1);
while(0);
syntax: while (boolean) statement 1;
example while(1);
while(0);
do-while loop is an exit-control loop. do-while loop execute statement at least once. because test condition evaluates at the bottom of loop.
Syntax:
do
{
statements;
}while(test-condition);
{
statements;
}while(test-condition);
Example:
int i=1;
do
{
printf("%d\n",i);
}while(i<10);
do
{
printf("%d\n",i);
}while(i<10);
No comments:
Post a Comment