What are the counter controlled and sentinel controlled loops?



Based on the nature of the control variables and the kind of value assigned to, the loops may be classified into two general categories; counter controlled and sentinel controlled loops.

Suggested Reading

3 Differences between counter and sentinel controlled loops. 

Counter controlled loops:

The type of loops, where the number of the execution is known in advance are termed by the counter controlled loop. That means, in this case, the value of the variable which controls the execution of the loop is previously known. The control variable is known as counter. A counter controlled loop is also called definite repetition loop.

Example: A while loop is an example of counter controlled loop.

sum = 0;
n = 1;
while (n <= 10){
     sum = sum + n*n;
     n = n+ 1;
     }

This is a typical example of counter controlled loop. Here, the loop will be executed exactly 10 times for n = 1,2,3,......,10.


ContentMiddleAd

Sentinel controlled loop:

The type of loop where the number of execution of the loop is unknown, is termed by sentinel controlled loop. In this case, the value of the control variable differs within a limitation and the execution can be terminated at any moment as the value of the variable is not controlled by the loop. The control variable in this case is termed by sentinel variable.
          
Example: The following do....while loop is an example of sentinel controlled loop.

do{
     printf(“Input a number.\n”);
     scanf("%d", &num);
     }
while(num > 0);

In the above example, the loop will be executed till the entered value of the variable num is not 0 or less then 0. This is a sentinel controlled loop and here the variable  num is a sentinel variable.

Suggested Reading:

3 Differences between counter and sentinel controlled loops. 

Recommended Recommends

Comments

Contact Us