Friday, July 17, 2020

Loop Control Structures

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:
  1. for loop
  2. while loop
  3. do-while loop
1. for loop


Syntax:

for ( initialisation expressions;
test expression;
update expression;)
body-of-the-loop;

Example:

int i; //declare variable
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)

case 2.:

for( ;test expression;update expression)

case 3.:

for(initialise exp; ;update expression)--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

2. while Loop
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

Example:

int i=0;
while(i<=10)
{
printf("%d",i);
i++;
}

Note:

repeat expression.
syntax: while (boolean) statement 1;
example while(1);
while(0);

3. do-while Loop
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);

Example:

int i=1;
do
{
printf("%d\n",i);
}while(i<10);

No comments:

Post a Comment