Sentinel Value in Java

Rupam Yadav Dec 02, 2021
Sentinel Value in Java

In a programming context, “sentinel” is a specific value used to terminate a condition in a recursive or looping algorithm. Sentinel value is used in many ways, such as dummy data, flag data, rouge value, or signal value.

Usage of Sentinel Value in a While Loop

This program reads input from the user and will print out the product of the input numbers. In the while loop condition which terminates it is if number != 0. This is the sentinel value that stops further execution of the loop. It allows users to know when they are done with the input.

The Sentinel value is not the part of the input which is to be processed.

The sentinel value must be of a similar data type, but it should differ from the normal input. It strictly depends on the user requirement of how many times a sentinel-controlled loop is supposed to run.

They get input from the user and use the Scanner class. As such, an object input of the Scanner class is created.

The user is asked to input any number other than 0 to continue. But, to stop the execution of the code further, the user has to enter 0.

To get the input numbers from the user, we call the nextInt() method on the input object. The user decides how often the loop is executed and when to end it.

The while loop receives numbers from the user until number zero is inputted. When the user inputs zero, the program should generate the product of all the numbers entered.

In a sentinel-controlled loop, the user can exit the loop on a specific condition as the condition doesn’t depend on a counter.

import java.util.Scanner;
public class SentinelTesting {
    public static void main(String [] args){

        int enteredNum, numberMultiplied, counter;
        counter = 0;
        numberMultiplied = 1;
        Scanner scannerObj = new Scanner(System.in);
        System.out.println("To move ahead, enter a number other than 0");
        enteredNum = scannerObj.nextInt();
        while (enteredNum != 0) {
            numberMultiplied = numberMultiplied*enteredNum;
            counter++;

            System.out.println("To proceed, enter a number other than 0");
            enteredNum = scannerObj.nextInt();
        }
        System.out.println("The result of multiplying the entered numbers = "+numberMultiplied);
    }
}

Output:

To move ahead, enter a number other than 0
10
To proceed, enter a number other than 0
20
To proceed, enter a number other than 0
5
To proceed, enter a number other than 0
0
The result of multiplying the entered numbers = 1000
Author: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn