Skip to main content

Section 5.5 Worked Example: Complex Conditional

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 50, 70, 80, 65, 90, 100, 0, 5, 102?

System.out.println("Enter a value. An invalid value will end input. ");
int pass = 0, fail = 0;
int value;
System.out.print ("Score: ");
Scanner get = new Scanner(System.in);
value = get.nextInt();
while (value >= 0 && value <= 100)
{
   if (value >= 70)
      pass++;
   else
      fail++;
   System.out.print("Score: ");
   value = get.nextInt();
}
System.out.println("Total number of scores: " + (pass + fail));
System.out.println("Pass: " + pass + "    Fail: " + fail);

Subsection 5.5.1 SG1: Diagram which statements go together.

Figure 5.5.1.

Subsection 5.5.2 SG2: Define and initialize variables

Start:

value = 50

End:

value < 0 OR
value > 100
Figure 5.5.2.

Subsection 5.5.3 SG3: Trace the loop

Figure 5.5.3.

Total number of scores: 8 Pass: 4 Fail: 4

Practice Pages.

You have attempted of activities on this page.