THE LOOP CONTROL STRUCTURE

Sometimes it is necessary in the program to execute the statement several times. Loops are used to execute a block of commands a specified number of times, until a condition is met. 
A program loop consists of 2 segments

1. Body of the loop 
2. Control statement.

The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. Depending on the position of the control statement in the loop, a loop may be classified as the entry controlled loop or as the exit–controlled loop.

Entry controlled loop
       In entry control loop, the execution first enters into the block of the loop where it checks the condition. If the condition is true, then  the body of the loop will be executed. Else it will not execute the body of the loop and exits from the loop.
Examples: For loop & While loop

Exit controlled loop
       In exit control loop first its runs the body of the loop then check the condition at the time of exit of the loop.If the condition is correct it will return to the entry of the loop otherwise it will exit.
Example:do-while loop


ENTRY CONTROLLED LOOP

While loop

While loop is used to repeat a section of the code until a specific condition is met. It is completed in three steps. They are variable initialization, condition, variable increment /decrement.
The syntax is as follows:

while(condition) {
   statement(s);
}

Example

#include <stdio.h>
 
int main () {

   
   int a = 10;
   while( a < 20 ) {
      printf("value of a: %d\n", a);
      a++;
   }
 
   return 0;
}




For loop

For loop is used to execute a set of statements repeatedly until a particular condition is satisfied.The for loop is distinguished from other looping statements through an explicit loop counter or loop variable which allows the body of the loop to know the exact sequencing of each iteration.
The syntax is as follows:

for ( init; condition; increment ) {
   statement(s);
}

Example

#include <stdio.h>
 
int main () {

   int a;
 
   for( a = 10; a < 20; a = a + 1 ){
      printf("value of a: %d\n", a);
   }
 
   return 0;
}



EXIT CONTROLLED LOOP

Do While loop

A do while loop is similar to while loop except the fact that it will execute the body of the loop at least once.
The syntax is as follows:

do {
   statement(s);
} while( condition );

Here the conditional expression appears at the end of the loop, so the statements in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statements in the loop executes again. This process repeats until the given condition becomes false.
#include <stdio.h>
 
int main () {

  
   int a = 10;

   do {
      printf("value of a: %d\n", a);
      a = a + 1;
   }while( a < 20 );
 
   return 0;
}

Comments

Popular posts from this blog

INTERFACING SEVEN SEGMENT DISPLAY WITH 89c51

INTERFACING OF LCD WITH 89C51

POINTERS