Skip to main content

Section 5.7 Worked Example: While Loops - Sentinel

Subgoals for Evaluating a Loop.

  1. Diagram which statements go together.

  2. Define and initialize variables

    1. Determine the start condition.

    2. Determine the update condition.

    3. Determine the termination condition.

    4. Determine body that is repeated.

  3. Trace the loop.

    1. For every iteration of the loop, write down the values.

You can watch this video or read through the content below it.

Problem: Given the following code, 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 5.7.1 SG1: Diagram which statements go together.

Figure 5.7.1.

Subsection 5.7.2 SG2: Define and initialize variables

Start:

score = 10;

End:

score < 0
Figure 5.7.2.

Subsection 5.7.3 SG3: Trace the loop

Figure 5.7.3.

Number of good scores: 4

Practice Pages.

You have attempted of activities on this page.