Sentinel-Controlled While Loop - Java Sample Program

//Sentinel-controlled while loop
//Filename:SentinelControlledWhileLoop.java

import java.util.*;
public class SentinelControlledWhileLoop
{
static Scanner console = new Scanner(System.in);
static final int SENTINEL = -999;

public static void main(String[] args)
{
int number; //variable to store the number
int sum = 0; //variable to store the sum
int count = 0; //variable to store the total numbers read

System.out.println("Line 1: Enter positive integers "+ "ending with " + SENTINEL); //Line 1
number = console.nextInt(); //Line 2

while (number != SENTINEL) //Line 3
{
sum = sum + number; //Line 4
count++; //Line 5
number = console.nextInt(); //Line 6
}

System.out.printf("Line 7: The sum of %d " + "numbers = %d%n", count, sum); //Line 7

if (count != 0) //Line 8
System.out.printf("Line 9: The average = %d%n", (sum / count)); //Line 9
else //Line 10
System.out.println("Line 11: No input."); //Line 11
}
}

/*
Sample Output: (In this sample run, the user input is shaded.)
***************************************************
Line 1: Enter positive integers ending with -999
34 23 9 45 78 0 77 8 3 5 -999
Line 7: The sum of 10 numbers = 282
Line 9: The average = 28
***************************************************

 This program works as follows: The statement in Line 1 prompts the user to enter
numbers and to terminate by entering -999. The statement in Line 2 reads the first
number and stores it in the variable number. The while statement in Line 3 checks
whether number is not equal to SENTINEL. If number is not equal to SENTINEL, the
body of the while loop executes.

 The statement in Line 4 updates the value of sum by
adding number to it. The statement in Line 5 increments the value of count by 1. The
statement in Line 6 stores the next number in the variable number. The statements in
Lines 4 through 6 repeat until the program reads -999. The statement in Line 7 outputs
the sum of the numbers, and the statements in Lines 8 through 11 output the average of
the numbers.

 Notice that the statement in Line 2 initializes the LCV number. The expression number
!= SENTINEL in Line 3 checks whether the value of number is not equal to SENTINEL.
The statement in Line 6 updates the LCV number. Also, note that the program continues
to read data as long as the user has not entered -999.

*/

No comments: