Sentinel-controlled while loop - Java tutorial with PRACTICAL example
Coding River
Sentinel-controlled while loop - Java tutorial with a PRACTICAL example
Hi and welcome back to this channel Today we are going to have a look at another form that a while loop may take in a program. Previously we talked about counter-controlled loops In this video particularly we will talk about another form of while loops which is called the Sentinel-controlled while loop This while loop form is often used when you do not know exactly how many times a set of statements needs to be executed But instead, you do know that the statements need to be executed until a special value is met. This special value is called a sentinel
The portion of code on the screen is a typical example of a Sentinel-controlled while loop
int sentinel = 100; int score =0;
while (score != sentinel) { System.out.print( score + “ “); score = score + 20; }
In this example, we have started by declaring and initializing the Sentinel variable, here sentinel Next, we have initialized the loop control variable score as well
In the while statement, we are using the loop condition to test the loop control variable score against the Sentinel variable sentinel
As long as, the loop control variable is different from the sentinel then the action statement will execute The first action statement will output the values of the variable score And the second action statement will increment the value of the variable score by 20, whenever the loop condition is met
Let’s take another example Suppose we want to create a program that will read integer values and sum them up. But we do not know exactly how many numbers the user needs to type in. So, in our program, we are going to determine an integer value that will be considered a Sentinel and that value will be used to mark the end of the input data.
In this program, I want the user to input data from the keyboard So, I will create an input object
static Scanner console = new Scanner(System.in);
Next, I will declare and initialize the Sentinel variable I prefer it to be a static variable static final int SENTINEL = 10;
public static void main(String[] args) {
Next, I need to declare the various variables that will be used in this program The first variable will be used to store the input numbers by the user int number; The second variable will hold the sum of all the numbers inputted by the user int sum = 0;
The third variable will be the loop control variable int counter = 0;
Next, we will write an output statement that will prompt the user to input the integer number System.out.println("Enter consecutive number and stop at " + SENTINEL);
Let’s write the input statement number = console.nextInt();
After, we will write the while loop statement The loop condition will test the variable number against the variable Sentinel whi ... https://www.youtube.com/watch?v=5wNEuIEoM0Q
14827109 Bytes