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



LoopWithSentinel Program


Description

There are a number of students, each with a test score.

This program inputs a test score for each student, calculates the average score, and finds the highest score
(assume there is no tie) until a sentinel value is entered.

Because we don't now in advance the number of students, so the sentinel-controlled while loop is used.

The sentinel is a special value to indicate the end of loop.

Associated Concepts:

Sentinel-controlled while loop

Algorithm:

Initialize sum and count variables to zero

Initialize highest variable to a very small number

Input a test score before entering the loop body

Use a sentinel-controlled while loop (-1 as the sentinel value)
(If the score is not equal to -1, the loop continues.)
(If the score is equal to -1, the loop ens.)

    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

    Input another test score at the end of the while loop body

Once the loop is ended, calculate the average

Print the result

Source Code



Sample Run



Video