In: Computer Science
Explain the similarities and differences of counter-controlled iteration and sentinel-controlled iteration. Also, give an example of how each would be used in a computer program.
Iterative:
The iterative statement like for() loop, while() loop, do-while() loop, etc uses the iterative statement and allows the set of instructions to be repeatedly executed. These statement includes initialization, condition, and update the control variable and repeatedly executed until a certain condition is reached.
Counter controlled iteration:
The counter controlled loops are executed for a specific number of times.
For example:
for() loop
The syntax for the 'for' loop is given below:
for(expression1, expression2, expression3)
{
//statement
}
The expression1 is executed only once and before the loop body execution.
The expression2 define a condition for the body of the loop
The expression3 is executed every time at the last of the loop body.
For example:
for(int i=0; i<10; i++)
{
//statements
}
The above 'for()' loop will execute for 10 times.
This loop should be used when we know the number of iteration in advance.
Sentinel controlled iteration:
Sentinel value is a special value that is used to terminate a condition in a loop or recursive execution.
For example:
For example:
while(condition)
{
//statements
}
The while loop will be executed until the condition is true and will exit when the condition will be false.
Difference:
The sentinel-controlled iteration can be used when we don't know the number of iteration in advance. Counter-controlled iteration can be used when we know the number of iteration in advance.
In sentinel-controlled iteration, the controlled variable is known as the sentinel variable but in the counter-controlled iteration, the controlled variable is known as a counter.
The example of sentinel-controlled iteration is while() and do-while() loops but the example of counter-controlled iteration is for() loop.
Similarities:
Both of the iterations are used to execute a group of statements or a single statement for a number of times.
Both of the iterations define an exit condition to avoid the infinite iteration.