Sentinel Loops
Learn and practice loops controlled by a sentinel value.
The sentinel value
Sometimes, the loop doesn’t have a fixed number of repetitions. Instead, an indicator value stops the loop. This special value is called the sentinel value. For example, we don’t know how much data is in a file without reading it all. However, we know that every file ends with an end-of-file (EOF) mark. So, the EOF mark is the sentinel value in this case.
Note: We should select a sentinel value that’s not expected in the normal input.
The while
loop
We use the while
loop when the termination of the loop depends on the sentinel value instead of a definite number of iterations.
As a simple example, we want to display the reverse sequence of digits in a positive integer value input by the user.
# Write your code here print("Enter the number: ") a = Integer(gets) # Taking input in variable a while a > 0 # This loop will terminate when the value is not greater than 0 print(a % 10) a /= 10 # Dividing a by 10 and assigning the result to variable a end print("\n")
In the program above:
- In the first line, we take input from the user.
- The loop statement,
while
, followed by a conditional expression. - The next two statements are in the body of the loop indicated by the indentation.
- The body of the loop executes if the condition expression
a > 0
istrue
. This statement tests the condition before entering the loop. Therefore, such a loop is called a pretest loop. - The loop terminates when the condition evaluates to
false
. - In the body of the loop, the first statement displays the value of the unit’s position using the modulo operation.
- The second statement strips that units value from
a
using integer division.
Sum the values using the while
loop
We want to sum the values provided by the user, stopping when the user inputs 0
. In this case, 0
is the sentinel value. Keep in mind that, while writing the program, we don’t know whether 0
will be the first input or the 100th.
Before showing the code captioned “Calculate the sum of the user inputs,” let’s use the next two programs to demonstrate some common mistakes that new learners might experience.
while a != 0 # This loop will terminate when the value of a is zero.print("Enter the number: ")a = Integer(gets) # Taking input from user in variable asum += a # Calculating the sumendprint("Sum is #{sum}\n")
First, let’s talk about the new elements that appear in the code above.
- The loop statement,
while
, is followed by a conditional statement. - The body of the loop executes if the condition
a != 0
istrue
. - The loop terminates when the condition evaluates to
false
. - In the body of the loop, the first statement asks for input from the user and stores it to
a
. - The second statement adds that value to the running
sum
being updated in the variablesum
on every iteration. - When the user inputs
0
, the loop terminates and moves to theprint()
statement outside the body of the loop. - The last statement displays the updated value of the
sum
variable.
What is the problem with the code above? There isn’t just a single problem.
The code has multiple syntax errors, which can be seen below:
- The variable,
a
, is not defined before its first usage in the condition. - The variable,
sum
, is not defined before its first usage insum += a
. The expanded meaning of this assignment statement issum = sum + a
. The variable,sum
, used on the RHS of the assignment must be defined first.
The following program fixes both syntax errors mentioned above. However, the code still doesn’t give the desired result. Now it has a logical error.
a = 0 sum = 0 while a != 0 # This loop will terminate when the value of a is zero. print("Enter the number: ") a = Integer(gets) # Taking input from user in variable a sum += a # Calculating the sum end print("Sum is #{sum}\n")
In the code above, there’s still the following problem:
- The value of
a
is already0
, which means the loop conditiona != 0
isfalse
because 0 != 0 isn’ttrue
. - We need to store some nonzero value as an initial value to
a
.
The following code is the correct executable code. To test this code, provide several inputs, one per line, in the input box titled “Enter the input below.”
a = 1 sum = 0 while a != 0 # This loop will terminate when the value of a is zero. print("Enter the number: ") a = Integer(gets) # Taking input from user in variable a sum += a # Calculating the sum end print("Sum is #{sum}\n")
The program will ignore 8
because it is written after 0
in the input box and 0
is the sentinel value (stopping criteria).
The execution sheet above illustrates how the pretest loop works with the help of loop unfolding. PS# 3 contains the loop condition, which is tested first. Then, PS# 4 and 5, containing the body of the loop, are executed. PS# 3, 4, and 5 keep on repeating until the condition in PS# 3 becomes false
. Only then will the execution jump to PS# 6 shown at ES# 16 above.
Note: Usually, we use a
while
loop when the loop termination depends on a specific event, like encountering a sentinel value. Thefor
loop is used when the number of iterations is definite. That’s why we call it a fixed iteration loop. However, both loops may be used interchangeably.
Practice for sentinel loops
The following are a few examples that can help you practice using the while
loop. By clicking the “Show Solution” button, you’ll find a program that solves the respective problem. You can copy and paste the given solution into the code widget to make sure that the output of your solution matches the given solution. There can be several ways to write correct solutions in programming.
Geometric sequence
Write a program that shows the terms of the geometric sequence that stops before the value exceeds .
# Write your code here
Average value
The average is calculated by dividing the sum of the values by their number.
Write a program that calculates the average of the numbers provided by the user. The program should stop and display the result when the user inputs 0
.
Sample input
5
10
15
0
Sample output
Average of inputs is: 10
# Write your code here
Greatest common divisor
The greatest common divisor is the largest integer which is an exact divisor of each of two other integers. Write a program that inputs two natural numbers from the user and displays their greatest common divisor (GCD) also known as the highest common factor (HCF).
Sample input 1
4
8
Sample output 1
The greatest common divisor is: 4
Sample input 2
400
600
Sample output 2
The greatest common divisor is: 200
# Write your code here