Sentinel Controlled While Loop
Submitted by GeePee on Tuesday, May 19, 2015 - 22:48.
The following java program application uses Sentinel Controlled While Loop. You might not know how many times a set of statements need to be executed, but you do know that the statements need to be executed until a special value is met. This special value is called a sentinel. . I will be using the JCreator IDE in developing the program.
To start in this tutorial, first open the JCreator IDE, click new and paste the following code:
Sample Run:
repeats until the programs reads -999.
The statement outputs the sum of the numbers, and the statements output the average of the numbers.
- import java.util.*;
- public class SentinelControlledWhileLoop
- {
- static final int SENTINEL = -999;
- {
- 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
- number = console.nextInt();
- while (number != SENTINEL)
- {
- sum = sum+number;
- count++;
- number = console.nextInt();
- }
- "numbers = %d%n", count, sum);
- if (count != 0)
- else
- }
- }
Enter positive integers ending with -999
10
19
-999
The sum of the 2 numbers = 19
The average = 9
This program works as follows:
The statement System.out.println("Enter positive integers ending with " + SENTINEL);
prompts the user to enter numbers ending with -999.
The statement number = console.nextInt();
reads the first number and stores it in the variable number
.
The while statement while (number != SENTINEL)
checks whether number is not equal to SENTINEL
. If number
is not equal to SENTINEL
, the body of the while loop executes.
The statement sum = sum+number;
updates the value of sum
by adding number to it.
The statement count++;
increments the value of count by 1.
The statement number = console.nextInt();
stores the next number in the variable number
.
The statements- sum = sum+number;
- count++;
- number = console.nextInt();
- "numbers = %d%n", count, sum);
Add new comment
- 136 views