COMP2243 - Programming and Problem Solving

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Repetitions/Loops WhileLoop.java LoopWithCounter.java LoopWithSentinel.java LoopWithFlag.java SimpleInterest.java Factorial.java Fibnonacci.java PrimeNumber.java GCD.java PopulationGrowth.java ForLoop.java DoWhileLoop.java FileIO_Tickets.java FileIO_Salary.java NestedLoop.java



LoopWithFlag Program


Description

This program is similar to LoopWithSentinel program.

We use a boolean value flag to control the loop execution.

Initially the flag is set to true.

If the user input is equal to the sentinel value, the flag is set to false to end the loop.

Associated Concepts:

Flag-controlled while loop

Algorithm:

Initialize sum and count variables to zero

Initialize highest variable to a very small number

Initialize flag to true

Use a flag-controlled while loop to input a test score for each iteration
(use -1 as the sentinel value)

    If the score is equal to the sentinel value, set the flag to false so the loop can end

    Otherwise

        If the input is valid

            Add the score to sum

            Increment count

            Assign the score to highest if the score is larger than the current highest value

        Otherwise

            Print an error message

Once the loop is ended, calculate the average

Print the result

Source Code



Sample Run



Video