3 Differences between counter and sentinel controlled loops

Last updated on July 4th, 2020 at 02:47 pm

Counter controlled loops are where we know the number of loop executions beforehand. Unlike counter controlled loops, in sentinel controlled loops the number of loop executions in unknow at the beginning and depends on decisions made inside the loop.

Read More: What are the counter controlled and sentinel controlled loops?

Differences between counter & sentinel controlled loops

The differences between the counter and sentinel controlled loops are as follows.

  • Number of executions: In case of counter controlled loops, we know the number of executions beforehand. On the other hand, in case of sentinel controlled loop, it depends on decisions made inside the loop
  • Loop controller: In case of counter controlled loops, the controller or condition variable is a counter. As because, it counts the total number of executions against the max number of executions. But in case of sentinel controlled loop, it is a sentinel, which means a guard. This variable waits for a decision made inside the loop to let another cycle take place or break the loop.
  • Value & max limit of controller variable: In counter controlled loop, the value of the loop controller variable and the limit it iterates to, both are strict. But in case of sentinel controlled loop, though the limit or condition is fixed, the value is variable as the value is set from inside the loop.

Lets write the differences in tabular format.

No.TopicsCounter controlled loopSentinel controlled loop
01Number of executionPreviously known number of executions take placeUnknown number of executions take place
02Condition variableCondition variable is known as counter variable. As because, it counts the total number of executions against the max number of executionsCondition variable is known as sentinel variable, which means a guard. This variable waits for a decision made inside the loop to let another cycle take place or break the loop
03Value and limitation of variableThe value of the variable and the limitation of the condition for the variable both are strict.The limitation for the condition variable is strict but the value of the variable varies in this case.
Differences between counter & controlled loops

Example

Counter controlled loop

int sum = 0;
int n = 1;

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

In this example. we can see that the while loop will only execute 10 times. The value and the limit both are fixed.

Sentinel controlled loop

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

In this example, we can see that the loop execution depends on user’s input. If the input is greater than 0, the loop continues. When the user inputs 0 or less than 0, the loop breaks.

Leave a Reply

Your email address will not be published. Required fields are marked *