Section 7.6 Worked Example: While Loops - Sentinel
Subgoals for Evaluating a Loop.
-
Identify loop parts
- Determine start condition
- Determine update condition
- Determine termination condition
- Determine body that is repeated
-
Trace the loop
- For every iteration of loop, write down values
Subsection 7.6.1
You can watch this video or read through the content below it.
Problem: The following code counts the number of valid values that are entered and stops when an invalid input is entered. What is the output if the user enters the values: 10, 15, 20, 25, 30, 35, -1?
System.out.println("Enter a negative score to signal the end of input.");
int gdScores = 0;
int score;
System.out.print("Score: ");
Scanner get = new Scanner(System.in);
score = get.nextInt();
while (score >= 0)
{
if (score >= 20)
gdScores++;
System.out.print("Score: ");
score = get.nextInt();
}
System.out.println("Number of good scores: " + gdScores);
Subsection 7.6.2 SG1: Diagram which statements go together.
Subsection 7.6.3 SG2: Define and initialize variables
Start:
score = 10;
End:
score < 0
Subsection 7.6.4 SG3: Trace the loop
Answer.
Number of good scores: 4
Practice Pages.
You have attempted of activities on this page.