Skip to main content

Section 7.9 Worked Example: For Loops - Sentinel

Subgoals for Evaluating a Loop.

  1. Identify loop parts
    1. Determine start condition
    2. Determine update condition
    3. Determine termination condition
    4. Determine body that is repeated
  2. Trace the loop
    1. For every iteration of loop, write down values

Subsection 7.9.1

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 up to 5 scores, or negative to end input.");
int gdScores = 0;
int score;
System.out.print ("Score: ");
Scanner get = new Scanner(System.in);
score = get.nextInt();
for (int m = 0; m < 5 && score >= 0; m++)
{
     if (score >= 20)
        gdScores++;
     System.out.print ("Score: ");
     score = get.nextInt();
}
System.out.println("Number of good scores: " + gdScores);

Subsection 7.9.2 SG1: Diagram which statements go together.

Figure 7.9.1.

Subsection 7.9.3 SG2: Define and initialize variables

Start:
score = 10, m = 0, gdScores = 0
End:
score < 0 OR
m >= 5
Figure 7.9.2.

Subsection 7.9.4 SG3: Trace the loop

Figure 7.9.3.
Number of good scores: 3

Practice Pages.

You have attempted of activities on this page.