Section 8.2 Worked Example: Writing Loops Part 2
Subgoals for Writing a Loop.
-
Determine purpose of loop
- Pick a loop structure (while, for, do_while)
- Define and initialize variables
-
Determine termination condition
- Invert termination condition to continuation condition
-
Write loop body
- Update loop control variable to reach termination
Subsection 8.2.1
You can watch this video or read through the content below it.
Problem: Write a loop that will prompt the user to continue to enter numbers until a sentinel value of -1 is entered and prints out the maximum value that was entered.
Subsection 8.2.2 SG1: Determine purpose of loop
Generally, while-loops are a good choice for sentinel loops.
Subsection 8.2.3 SG2: Define and initialize variables
We will need variables to store the most recent input value, as well as the maximum value so far.
We will also need a Scanner to accept user input, as well as a priming read.
Scanner get = new Scanner(System.in);
int value;
int maxSoFar;
System.out.println("Enter a value, enter -1 to end");
value = get.nextInt();
while ( )
{
}
Subsection 8.2.4 SG3: Define termination condition invert to continuation condition
We want to stop reading values when the sentinel value of -1 is read. So the termination condition is:
value == -1
Subsection 8.2.5 SG4a: Update condition (LCV) to reach termination
To invert that condition to become a continuation condition looks like:
Scanner get = new Scanner(System.in);
int value;
int maxSoFar;
System.out.println("Enter a value, enter -1 to end");
value = get.nextInt();
while ( value != -1 )
{
System.out.println("Enter a value, enter -1 to end");
value = get.nextInt();
}
Subsection 8.2.6 SG4: Write loop body
Finding the maximum value is a common algorithm. The basic pieces of the algorithm are:
- Initialize a variable to hold the first value
- If the next value is larger than the value stored, then store the new value as the maximum
- Continue until all values have been processed
In the following code, notice the new variable declaration maxSoFar to hold the maximum value. It is initialized to the sentinel value since we know all valid values entered must be larger than the sentinel value. Inside the loop, we compare the newest value read to the value in maxSoFar and the larger value is stored. Notice the if statement after the loop which accounts for the fact that no valid values may have been entered.
Scanner get = new Scanner(System.in);
int value;
int maxSoFar = -1;
System.out.println("Enter a value, enter -1 to end");
value = get.nextInt();
while ( value != -1 )
{
if (value > maxSoFar)
maxSoFar = value;
System.out.println("Enter a value, enter -1 to end");
value = get.nextInt();
}
if (maxSoFar > -1)
System.out.println("The maximum is " + maxSoFar);
else
System.out.println("No values entered");
Practice Pages.
You have attempted of activities on this page.