Study Guide

Tackling a Programming Scenario

How to turn a long written description of a problem into a working algorithm: annotate the requirements, break the problem into parts, choose arrays and variables, write and test it in stages, and check it against the original words. One scenario is worked in full; a second is for you to write.

Lesson 5.16 Algorithms and Programming

For: Cambridge IGCSE Computer Science learners preparing for the longest question on Paper 2, or learners who can write loops, arrays and validation and want to put them together (about ages 14 to 16)

Stage: Think

A page of words

Riverside School (a fictional school) is holding its sports day, and the teacher in charge of the long jump has asked for a program. This is what she has written:

Five pupils take part in the long jump. The program must:

  1. ask for the name and the jump distance in metres of each of the five pupils;
  2. accept a distance only if it is from 0 to 10 metres, and otherwise show a message and ask again;
  3. store every name and every distance;
  4. work out the average distance and output it;
  5. find the pupil who jumped furthest and output their name and distance;
  6. count the pupils who reached the qualifying distance of 4.5 metres or more, and output the count.

A longer question like this is easy to start in the wrong place. You are going to follow a method instead.

Think it through

Before writing any code, read the six requirements again. List what the program takes in, what it has to work out, what it has to remember, what it outputs and what rules it must follow.

Show a model answer

Inputs: five names and five distances. Rule (validation): each distance must be from 0 to 10; otherwise a message and another go. Storage: every name and every distance, kept until the end, because the winner needs both. Processes: the average (a total, then a division), the furthest jump (a highest value, remembering whose it is) and a count of the distances that are 4.5 or more. Outputs: the average, the winner’s name and distance, and the count. Seeing the requirements as these five kinds of thing shows what the program must contain before any code is written.

Stage: Discover

Breaking it into smaller jobs

Think it through

Break the problem into four or five smaller jobs, in the order the program would do them. Each should be small enough that you could write it on its own.

Show a model answer

One good order: (1) get one pupil’s name and a valid distance and store them, repeated for all five; (2) while doing so, add each distance to a total, keep track of the furthest jump so far and count the distances that reach 4.5; (3) when all five are in, work out the average; (4) output the average, the winner and the count. The results depend on all the data, so they can only be output after the loop.

Splitting a problem into smaller parts that can each be solved on their own is decomposition. It is the same idea as the structure diagrams in Lesson 1, used here on a written scenario: each smaller job becomes a few lines of the program, and the order of the jobs becomes the order of the code.

Here is each part of the requirements, to be sorted into the kinds of thing found in the first step:

What kind of thing is each part of the requirements?
Part of the requirementsInput, process, output or storage?
asks for the name and distanceInput
accepts a distance only from 0 to 10, otherwise asks again
stores every name and distance
works out the average distance
outputs the average distance
finds the pupil who jumped furthest
outputs their name and distance
counts the pupils who reached 4.5 metres or more

    Show the completed table
    Part of the requirementsInput, process, output or storage?
    asks for the name and distanceInput
    accepts a distance only from 0 to 10, otherwise asks againProcess
    stores every name and distanceStorage
    works out the average distanceProcess
    outputs the average distanceOutput
    finds the pupil who jumped furthestProcess
    outputs their name and distanceOutput
    counts the pupils who reached 4.5 metres or moreProcess

    Stage: Predict

    Where the data lives

    Think it through

    The program must still know all five names and distances when it has finished the input, because the winner’s name is needed at the end. How would you store them? Why would five separate variables for the names and five for the distances be a poor choice?

    Show a model answer

    Use arrays: one for the names and one for the distances, each with five elements. Ten separate variables would need ten separate lines to fill and to search, and a program for fifty pupils would need a hundred. An array can be filled and searched with one loop, whatever its size.

    Two arrays do the job. Each holds one kind of data, but they are kept in step: the name in Names[3] belongs to the distance in Distances[3], because both use the same position for the same pupil.

    DECLARE Names : ARRAY[1:5] OF STRING
    DECLARE Distances : ARRAY[1:5] OF REAL

    Two other values will be needed as the program works: a total (for the average) and a count of the pupils who reached the qualifying distance. A third records which position holds the furthest jump so far. Remembering the position and not the distance lets the program find both the distance and the name.

    Check your understanding

    Why must Names and Distances use the same position for the same pupil?
    Show the answer

    Answer: C. Because one position then finds both name and distance.

    Parallel arrays work because position joins them.

    Stage: Explain

    Writing the first part, and testing it

    Think it through

    Which part of the program would you write first, and would you write the whole program and then test it, or test as you go? Say why.

    Show a model answer

    The input and validation come first, because everything else depends on the data being stored correctly. Testing as you go is better: if you test after each part, a mistake must be in the part you have just added, so it is quick to find. If you write everything and then test, a mistake could be anywhere.

    Writing the whole program in one go and testing it only at the end hides where mistakes are. Write one part, test it, then add the next part. A part that has been tested is a safe base for the next.

    1. Choose the loop. There are exactly five pupils, so a FOR loop with Index going from 1 to 5.
    2. Read the name into Names[Index], so each pupil’s name goes in its own position.
    3. Read the distance with validation. A REPEAT … UNTIL loop inside the FOR loop, because the distance must be asked for at least once. The IF shows a message for a refused distance, and the UNTIL condition is the allowed range, Distances[Index] >= 0 AND Distances[Index] <= 10.
    4. Test this part alone, with a normal distance and with a refused one, before adding anything else.
    DECLARE Names : ARRAY[1:5] OF STRING
    DECLARE Distances : ARRAY[1:5] OF REAL
    FOR Index ← 1 TO 5
      OUTPUT "Enter the name of pupil ", Index
      INPUT Names[Index]
      REPEAT
        OUTPUT "Enter the distance in metres (0 to 10)"
        INPUT Distances[Index]
        IF Distances[Index] < 0 OR Distances[Index] > 10
          THEN
            OUTPUT "The distance must be from 0 to 10. Please try again."
        ENDIF
      UNTIL Distances[Index] >= 0 AND Distances[Index] <= 10
    NEXT Index

    Test it for pupil 2, Ben, who first types 51 (a slip) and then 5.1:

    Pupil 2 types 51 and then 5.1
    AttemptDistance typedMessage shown?Does the REPEAT loop end?Distances[2] afterwards
    15151
    25.1

      Show the completed table
      AttemptDistance typedMessage shown?Does the REPEAT loop end?Distances[2] afterwards
      151YesNo51
      25.1NoYes5.1

      Check your understanding

      Which is the best order for writing and testing the program?
      Show the answer

      Answer: B. Write and test the input first, then add one calculation at a time.

      Build on a part that has been tested.

      Stage: Predict

      Adding the calculations

      The data is now stored. Three results are still needed: the average (a total divided by 5), the furthest jump, and the number of pupils who reached 4.5 metres. Each is one of the standard methods from Lesson 6, and each can be added to the same loop, after the validation.

      Think it through

      Which variables does stage two need, what should each start as, and where should those starting values be set?

      Show a model answer

      A total (start 0), a count of qualifiers (start 0) and the position of the furthest jump so far (start 1, so that the first pupil is the first candidate). All three are set before the loop, never inside it, otherwise they would be reset on every pass.

      // Long jump results for five pupils
      CONSTANT QualifyingDistance ← 4.5
      DECLARE Names : ARRAY[1:5] OF STRING
      DECLARE Distances : ARRAY[1:5] OF REAL
      DECLARE Total : REAL
      DECLARE Winner : INTEGER
      DECLARE Qualified : INTEGER
      Total ← 0
      Winner ← 1
      Qualified ← 0
      FOR Index ← 1 TO 5
        OUTPUT "Enter the name of pupil ", Index
        INPUT Names[Index]
        REPEAT
          OUTPUT "Enter the distance in metres (0 to 10)"
          INPUT Distances[Index]
          IF Distances[Index] < 0 OR Distances[Index] > 10
            THEN
              OUTPUT "The distance must be from 0 to 10. Please try again."
          ENDIF
        UNTIL Distances[Index] >= 0 AND Distances[Index] <= 10
        Total ← Total + Distances[Index]
        IF Distances[Index] > Distances[Winner]
          THEN
            Winner ← Index
        ENDIF
        IF Distances[Index] >= QualifyingDistance
          THEN
            Qualified ← Qualified + 1
        ENDIF
      NEXT Index
      OUTPUT "Average distance: ", Total / 5
      OUTPUT "Winner: ", Names[Winner], " with ", Distances[Winner], " metres"
      OUTPUT "Pupils who reached ", QualifyingDistance, " metres: ", Qualified

      Follow the calculations for the five pupils Aisha (4.2), Ben (5.1), Chloe (3.8), Dev (5.6) and Ella (4.9). Each row shows the variables after that pupil has been dealt with:

      Following the calculations for five pupils
      IndexDistanceTotalWinnerQualified
      14.24.210
      25.1
      33.8
      45.6
      54.9

        Show the completed table
        IndexDistanceTotalWinnerQualified
        14.24.210
        25.19.321
        33.813.121
        45.618.742
        54.923.643

        The outputs are: Average distance: 4.72 (23.6 divided by 5), Winner: Dev with 5.6 metres, and Pupils who reached 4.5 metres: 3.

        Check your understanding

        Why does the program keep the position of the furthest jump in Winner, and not the distance itself?
        Show the answer

        Answer: D. The position is needed to get the winner’s name, as well as the distance.

        Remember a position when you will need more than one fact about the item.

        Stage: Apply

        Testing with chosen data

        Think it through

        Choose test data for the distance rule, 0 to 10 metres, including normal, extreme, boundary and abnormal data, and state whether each should be accepted. Which four values are the boundary data?

        Show a model answer

        Normal: 5.5 (accepted). Extreme: 0 and 10 (accepted). Boundary: 0 and 10 (accepted), and -0.1 and 10.1 (refused), the nearest refused values with one decimal place. Abnormal: -4 and 51 (refused), and a word such as “far” (refused by a type check in a real program). The boundary data are 0, 10, -0.1 and 10.1.

        A test plan for the long jump distance rule (0 to 10 metres)
        Distance typedType of test dataExpected result
        5.5NormalAccepted
        0
        10
        -0.1
        10.1
        51

          Show the completed table
          Distance typedType of test dataExpected result
          5.5NormalAccepted
          0Extreme and boundaryAccepted
          10Extreme and boundaryAccepted
          -0.1BoundaryRejected
          10.1BoundaryRejected
          51AbnormalRejected

          A last step is to read the six requirements again, one at a time, and tick each against the program: (1) the loop asks for each name and distance; (2) the REPEAT … UNTIL loop refuses and asks again; (3) both arrays hold every value; (4) the average is output after the loop; (5) Winner finds the furthest jump; (6) Qualified counts distances of 4.5 or more. A requirement with nothing in the program to match it is a gap.

          Check your understanding

          A programmer has typed UNTIL Distances[Index] > 0 AND Distances[Index] < 10 by mistake. Which test value from the plan shows this?
          Show the answer

          Answer: A. 0, which should be accepted but would be refused.

          Boundary data finds a mistake in a limit.

          Stage: Explain

          The method, in six moves

          Think it through

          Look back over what you have done in this lesson. In your own words, list the moves that took you from the page of words to a tested program, in order.

          Show a model answer

          Read and annotate the requirements; break the problem into smaller jobs; choose the arrays and variables; write the first stage and test it; add the calculations and test; then test the whole thing with chosen data and check each requirement against the program.

          Six moves for any scenario

          The same moves worked in the long jump program, in the order to do them.

          1. You

            Step 1 of 6: Read and annotate

            Mark the inputs, the data to store, the calculations, the outputs and any rules (such as a valid range).

            Technical detail: In the long jump: five names and distances in; a rule of 0 to 10; an average, a winner and a count out.

          2. You

            Step 2 of 6: Break it into jobs

            List smaller jobs in the order the program will do them. The order of the jobs becomes the order of the code.

          3. You

            Step 3 of 6: Choose where the data lives

            Decide which arrays and which single variables are needed, what each starts as, and where the starting values are set.

          4. You

            Step 4 of 6: Write one stage and test it

            Start with the input and validation. Add one calculation at a time, testing each addition.

          5. You

            Step 5 of 6: Test the whole program

            Choose test data in advance, with the expected results worked out before running anything: normal, extreme, boundary and abnormal.

          6. You

            Step 6 of 6: Check against the words

            Read the requirements again, one at a time, and find the lines of the program that meet each. Tidy the names and add comments.

          A real exam question gives about half an hour for this, so the first two moves matter most: a few minutes spent reading and planning save time later.

          Apply it

          Sam starts writing code as soon as the question appears, and later finds that the program does not refuse a distance of 12. Which move did Sam probably skip or rush?
          Show the answer

          Answer: C. Read and annotate, so the range rule was never noticed.

          The early moves decide what the program must contain.

          Go deeper The long jump program in Python

          The exam allows pseudocode or a named programming language such as Python. This version follows the same plan, with lists in place of arrays (Python counts positions from 0).

          QUALIFYING_DISTANCE = 4.5
          names = []
          distances = []
          total = 0
          winner = 0
          qualified = 0
          for index in range(5):
              names.append(input("Enter the name of pupil " + str(index + 1) + ": "))
              distance = float(input("Enter the distance in metres (0 to 10): "))
              while distance < 0 or distance > 10:
                  print("The distance must be from 0 to 10. Please try again.")
                  distance = float(input("Enter the distance in metres (0 to 10): "))
              distances.append(distance)
              total = total + distance
              if distance > distances[winner]:
                  winner = index
              if distance >= QUALIFYING_DISTANCE:
                  qualified = qualified + 1
          print("Average distance:", round(total / 5, 2))
          print("Winner:", names[winner], "with", distances[winner], "metres")
          print("Pupils who reached", QUALIFYING_DISTANCE, "metres:", qualified)

          For the five pupils above this prints Average distance: 4.72, Winner: Dev with 5.6 metres and Pupils who reached 4.5 metres: 3. round(…, 2) is used because a computer adds decimals in binary, so a total such as 23.6 can come out with a tiny extra fraction in the last place. Python’s while loop tests first, so the first distance is read before it and again at the end of each pass.

          Stage: Apply

          Now write one yourself

          The Riverside School canteen (fictional) sells five snacks. The arrays Snack and Price already hold the names and the prices in pence, as in this list, in the same order.

          • Position 1: Flapjack, 90 pence
          • Position 2: Apple, 50 pence
          • Position 3: Crisps, 60 pence
          • Position 4: Cookie, 75 pence
          • Position 5: Juice, 80 pence

          At the end of the day the manager types in how many of each snack were sold. The program must:

          1. ask for the number sold of each snack, using the snack’s name in the question;
          2. accept a number only if it is a whole number from 0 to 200, and otherwise show a message and ask again;
          3. work out and output the total money taken, in pence;
          4. output the name of the best-selling snack (the one with the most sold);
          5. output the name of every snack that sold fewer than 10.

          Think it through

          Follow the six moves. Annotate the requirements, list the jobs, choose the arrays and variables, and then write the algorithm in pseudocode or Python. Test it with 40, 8, 25, 60 and 9 sold, and say what it should output.

          Show a model answer
          // Snack and Price are given: they hold the snack names and prices in pence
          DECLARE Sold : ARRAY[1:5] OF INTEGER
          DECLARE Total : INTEGER
          DECLARE BestSnack : INTEGER
          Total ← 0
          BestSnack ← 1
          FOR Index ← 1 TO 5
            REPEAT
              OUTPUT "How many ", Snack[Index], " were sold today (0 to 200)?"
              INPUT Sold[Index]
              IF Sold[Index] < 0 OR Sold[Index] > 200
                THEN
                  OUTPUT "Please enter a whole number from 0 to 200."
              ENDIF
            UNTIL Sold[Index] >= 0 AND Sold[Index] <= 200
            Total ← Total + Sold[Index] * Price[Index]
            IF Sold[Index] > Sold[BestSnack]
              THEN
                BestSnack ← Index
            ENDIF
          NEXT Index
          OUTPUT "Money taken (pence): ", Total
          OUTPUT "Best seller: ", Snack[BestSnack]
          OUTPUT "Snacks that sold fewer than 10:"
          FOR Index ← 1 TO 5
            IF Sold[Index] < 10
              THEN
                OUTPUT Snack[Index]
            ENDIF
          NEXT Index

          For 40, 8, 25, 60 and 9 it should output: Money taken (pence): 10720 (3600 + 400 + 1500 + 4500 + 720); Best seller: Cookie; and then Apple and Juice as the snacks that sold fewer than 10. The type check (a whole number) is a part of requirement 2 that pseudocode usually states in words, such as “check that the number is an integer”.

          When you have written your own, compare it with this checklist. It is our own description of what a strong answer to this scenario shows, written for this lesson. It is not an examination board’s mark scheme, and it says nothing about how many marks an answer would receive.

          • It uses an array for the numbers sold, and a loop that covers all five snacks, with the right first and last positions.
          • It validates each number, repeating the question with a message until the number is from 0 to 200, and the limits 0 and 200 are themselves allowed.
          • It sets the total to 0 before the loop, and adds the number sold times the price for each snack, not just the number sold.
          • It finds the best seller with a sensible start, and remembers the position so that the name can be output.
          • It checks each snack against 10 (fewer than 10, so a comparison with < 10) and outputs the name of each one that qualifies.
          • Its outputs are labelled so that a reader knows what each shows.
          • Its names are meaningful, it is indented and it has a comment saying what it does.
          • It would give the right results for test data worked out in advance, including the limits 0 and 200 and the values 9 and 10.

          Apply it

          A learner’s answer has Total ← Sold[Index] * Price[Index] inside the loop, in place of the line that adds. With the data 40, 8, 25, 60 and 9, what is wrong, and what does it output for the total?
          Show the answer

          Answer: D. It outputs 720, as only the last snack’s money is kept.

          A total adds to what it already holds; assigning replaces it.

          Stage: Consolidate

          Show what you know

          Think it through

          In a 30-minute scenario question, you have just read the whole description. What do you do in the first five minutes before writing any code, and why does it help?

          Show a model answer

          A good answer says to read the scenario through, annotate it (underline the inputs, the data to store, the calculations, the outputs and the rules), list the smaller jobs in order, and decide which arrays and variables are needed and what they start as. It helps because every requirement is then noticed once, the program has a plan to follow, and the code can be written and tested stage by stage with fewer surprises.

          Apply it

          A new scenario says: “the program stores the ages of 20 members of a swimming club and outputs the number who are under 12”. Which pair of choices is the best start?
          Show the answer

          Answer: B. An array of 20 ages, a FOR loop, and a counter starting at 0.

          Choose structures to suit the data and the methods the scenario names.

          • Annotate the scenario first: inputs, data to store, calculations, outputs and rules.
          • Decomposition gives the order of the program: input and validate, calculate, then output.
          • Use arrays for lists of one kind of data, kept in step by position; set totals, counts and positions before the loop.
          • Write one stage, test it, then add the next. Choose test data in advance, including the limits.
          • Finish by checking each requirement against the program, with clear names and comments so that it is maintainable.

          Sources and scope

          • What this lesson is. The sixteenth lesson of the Algorithms and Programming module, written for this site. It covers point 7.9 of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6) and draws on points 7.2 to 7.7 and 8.1 to 8.2. It follows the description of the Paper 2 scenario question in section 4 of the syllabus: an unseen 15-mark question, answered in pseudocode or a named programming language, for which about thirty minutes is expected. Its curriculum links are provisional and imply no review or endorsement by any examination board.
          • Original material. Riverside School, the sports day, the canteen, Sam and every name and number in the two scenarios are fictional, written for this lesson. The checklist of what a strong answer shows is our own wording; this lesson does not reproduce or describe any official mark scheme. Each trace and output was worked out by hand, and the Python was run.
          • Simplified on purpose. The scenarios are shorter than an examination question, so that each stage can be seen. The type check is described in words, and ties for the highest value are decided in favour of the first.
          • Left to other lessons. Flowcharts for scenarios, two-dimensional arrays in scenarios and files in scenarios; each can be combined with the methods here after Lessons 10 and 15.