Guide 3.5 of 7

Max, Min, Counting & Totaling

Common algorithms used inside loops for AQA, OCR, and Cambridge IGCSE / A-Level Computer Science.

Quick Reference:
  • Counting - Incrementing a variable to keep track of occurrences.
  • Totaling - Accumulating a running sum of values.
  • Finding Max & Min - Storing the largest or smallest value seen so far.

Counting

Counting is used to find out how many times an event occurs or how many items meet a certain condition. You always initialize the count to 0 before the loop, and increment it by 1 inside the loop.

Hover to Reveal Example
DECLARE Count : INTEGER
DECLARE LoopIndex : INTEGER
DECLARE UserInput : INTEGER

Count ← 0

FOR LoopIndex ← 1 TO 5
    OUTPUT "Enter a number: "
    INPUT UserInput
    IF UserInput > 10 THEN
        Count ← Count + 1
    ENDIF
NEXT LoopIndex

OUTPUT "You entered ", Count, " numbers greater than 10."

Totaling

Totaling (or accumulating) keeps a running sum. Initialize the total to 0 before the loop, and add the current value to it inside the loop.

Hover to Reveal Example
DECLARE Total : INTEGER
DECLARE LoopIndex : INTEGER
DECLARE UserInput : INTEGER

Total ← 0

FOR LoopIndex ← 1 TO 3
    OUTPUT "Enter a price: "
    INPUT UserInput
    Total ← Total + UserInput
NEXT LoopIndex

OUTPUT "The total price is: ", Total

Finding Maximum and Minimum

To find the largest or smallest value in a sequence, you need a variable to store the "best seen so far". You can initialize the Max and Min variables in two ways:

  1. Method 1: First Input - Read the first value outside the loop and set it as both Max and Min. This is the safest method.
  2. Method 2: Extreme Values - Initialize Max to a very small number (e.g. -9999) and Min to a very large number (e.g. 9999).
Hover to Reveal Example
DECLARE MaxValue : INTEGER
DECLARE MinValue : INTEGER
DECLARE CurrentNum : INTEGER
DECLARE LoopIndex : INTEGER

// Initialize with the first input
OUTPUT "Enter number 1: "
INPUT CurrentNum
MaxValue ← CurrentNum
MinValue ← CurrentNum

// Loop for the remaining numbers
FOR LoopIndex ← 2 TO 5
    OUTPUT "Enter number ", LoopIndex, ": "
    INPUT CurrentNum
    
    IF CurrentNum > MaxValue THEN
        MaxValue ← CurrentNum
    ENDIF
    
    IF CurrentNum < MinValue THEN
        MinValue ← CurrentNum
    ENDIF
NEXT LoopIndex

OUTPUT "Maximum: ", MaxValue
OUTPUT "Minimum: ", MinValue

Ready to practice?

Try running these algorithms step-by-step using our Trace Table generator!

Learn Trace Tables