Sentinel Loops
Learn and practice loops controlled by a sentinel value.
We'll cover the following...
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.
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter a number: ");
int a = myObj.nextInt(); // Taking input in variable a
while (a > 0)// This loop will terminate when the value is not greater than 0
{
System.out.println(a % 10);
a /= 10; //Dividing a by 10 and assigning the result to variable a
}
}
}In the program above:
-
Line 1: We import the
Scannerclass. -
Line 6: We create a
Scannerobject namedmyObj. -
Line 8: We take input from the user and store it in variable
a. -
Line 9: The body of the
whileloop executes if the condition expressiona > 0istrue. This statement tests the condition before entering the loop. Therefore, such a loop is called a pretest loop.Note: There is no semicolon (
;) at the end of line 9. -
The loop terminates when the condition evaluates to
false. -
...