Question: While Loops: Sentinel Values Tutorial: Sentinel Controlled While Loops A sentinel - controlled while loop is a type of while loop that continues to execute
While Loops: Sentinel Values
Tutorial: Sentinel Controlled While Loops
A sentinelcontrolled while loop is a type of while loop that continues to execute until a specific value, known as a sentinel value, is encountered. The sentinel value acts as the signal for the while loop to stop executing. These are best used when the number of iterations the loop should run is unknown.
One example is say we are repeating code until a user enters a particular value. We can continue looping until we receive this value from input. We do not know how many times our loop will run, this is dependent on the inputs we receive. As soon as we get the specified value to stop though, our loop will finish and our program will continue on with anything left over.
These loops still have all three components every while loop needs being:
Control variable
Loop condition
Update to the control variable so that the condition eventually becomes False
Try the code below:
sentinel inputEnter a message to print Quit to stop:
while sentinel "Quit":
printsentinel
sentinel inputEnter a message to print Quit to stop:
printLoop terminated because sentinel value Quit was entered.
Code Visualizer
TRY IT
Work to identify the following questions:
What is the control variable?
What is the loop condition?
What is the update to the control variable?
How many times will the input message be printed?
Try creating a program that counts the number of even numbers entered and the number of odd numbers entered. The program should continue until is entered. should also not be counted as an even or an odd number for this problem. The input prompts should all be:
Enter a number:
Note: There is a space and a newline after the colon.
After the loop has finished, print out the following:
There were eNums even numbers.
There were oNums odd numbers.
Replace eNums with how many even numbers there were and replace oNums with how many odd numbers there were.
Hint: Use variables to count the number of even numbers entered and the number of odd numbers entered.
Hint : How do we know if a number is even or odd? Try thinking of how modulo can be used to accomplish this.
TRY IT
Below is a sample run as it would appear in the terminal:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
There were even numbers.
There were odd numbers.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
