Cambridge IGCSE0478

Algorithm design and problem-solving

Computer Science 0478 Chapter Notes

What this chapter covers

Algorithm design and problem-solving
ShareWhatsAppPost
Algorithm design and problem-solving notes

Unable to load PDF

The notes viewer could not load. Please refresh the page.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Algorithm design and problem-solving notes as text: skim, search, and jump between subtopics.

~15 min read

1. The Program Development Life Cycle

The Program Development Life Cycle (PDLC) is a structured, step-by-step process that professionals follow to create high-quality software. It's not a one-time process but a cycle, meaning developers often revisit earlier stages to make improvements. Following these stages helps ensure the final program is well-designed, works correctly, and meets the user's needs. The main stages are Analysis, Design, Coding, and Testing.

Key term

Program Development Life Cycle (PDLC): A structured, multi-stage process for creating high-quality software from initial concept to final deployment and maintenance.

Examiner insight

Examiners look for a clear description of each stage, not just its name. For a 'describe' question, always provide a sentence explaining what happens in that stage.

Worked example 14 marks

One stage of the program development life cycle is Coding. Identify and describe two other stages. [4]

  1. 1

    Stage 1: Analysis. [1] This is the first stage where the requirements for the system are gathered. The programmer must understand exactly what the problem is and what the program needs to do. [1]

  2. 2

    Stage 2: Design. [1] In this stage, the programmer plans the solution. This involves creating algorithms (using pseudocode or flowcharts), planning data structures, and designing the user interface. [1]

Recap

  • The PDLC is a structured process for building software.
  • The Analysis stage is about understanding and defining the problem.
  • The Design stage involves planning the solution using tools like pseudocode.
  • The Coding stage is where the program is written in a programming language.
  • The Testing stage involves finding and fixing errors in the program.

Quick check

  1. In which stage of the PDLC would you draw a flowchart?1 mark
  2. What is the main goal of the Analysis stage?1 mark

2. Decomposition and Structure Diagrams

Complex problems are difficult to solve all at once. Decomposition is the technique of breaking down a large, complex problem into smaller, more manageable sub-problems. This is also known as 'top-down design'. Each sub-problem can then be solved independently, and sometimes broken down even further. A structure diagram is a visual tool used to show how a system is decomposed. It's a hierarchical chart that shows the main problem at the top, with the sub-problems branching out underneath it.

Key term

Decomposition: The process of breaking down a complex problem or system into smaller, more manageable sub-problems.

Examiner insight

Examiners reward clear, hierarchical structure diagrams that show a logical breakdown of the main problem into distinct sub-tasks. Ensure lines clearly connect parent modules to their children.

Fun fact

The 'divide and conquer' strategy used in decomposition is a fundamental concept in computer science, used in many famous algorithms like Merge Sort and Quick Sort.

Worked example 14 marks

A simple video game needs to be developed. The main functions are to 'Play Game', manage 'High Scores', and change 'Settings'. The 'Play Game' function involves 'Moving the Player', 'Spawning Enemies', and 'Calculating Score'. Create a structure diagram to represent this decomposition. [4]

  1. 1
    1. Start with the main system at the top: 'Video Game'.
  2. 2
    1. Draw branches to the first level of sub-problems: 'Play Game', 'High Scores', and 'Settings'.
  3. 3
    1. Under the 'Play Game' module, draw further branches to its sub-problems: 'Move Player', 'Spawn Enemies', and 'Calculate Score'.
  4. 4
    1. The final diagram should be a clear hierarchy, with 'Video Game' at the root, connecting down to its sub-modules.
  5. 5

    Example Diagram Layout:

  6. 6

    [Video Game]

  7. 7

    |

  8. 8

    +---------------+---------------+

  9. 9

    | | |

  10. 10

    [Play Game] [High Scores] [Settings]

  11. 11

    |

  12. 12

    +---------------+---------------+

  13. 13

    | | |

  14. 14

    [Move Player] [Spawn Enemies] [Calculate Score]

Recap

  • Decomposition makes complex problems easier to solve.
  • It involves breaking a problem into smaller sub-problems.
  • A structure diagram visually represents the decomposition of a system.
  • Structure diagrams show the hierarchy and relationships between modules.
  • This approach is also called top-down design.

Quick check

  1. What is another name for the technique of decomposition?1 mark

3. Designing Algorithms: Flowcharts & Pseudocode

Before coding, you must design your algorithm. Two standard methods for this are flowcharts and pseudocode. A flowchart is a diagram that uses standard symbols to represent the different actions and decisions in an algorithm. Pseudocode is a way of describing an algorithm using structured English-like statements. It is not an actual programming language, so it has no strict syntax rules, but it should be clear, precise, and unambiguous. Both methods help you plan the logic of your program without worrying about the specific syntax of a programming language.

Key term

Pseudocode: A plain-language description of the steps in an algorithm or another system, intended for human reading rather than machine reading.

Common pitfall

Using language-specific syntax (like Python's `elif` or Java's `++`) in pseudocode. Pseudocode should be generic and understandable to any programmer.

Worked example 16 marks

Design an algorithm that asks a user to enter a number. If the number is greater than 10, it should output 'High'; otherwise, it should output 'Low'. Represent this algorithm as both a flowchart and in pseudocode. [6]

  1. 1

    Flowchart:

  2. 2
    1. Start with a 'Start' terminator (oval).
  3. 3
    1. Use a parallelogram for 'INPUT Number'.
  4. 4
    1. Use a diamond for the decision 'Is Number > 10?'.
  5. 5
    1. From the 'Yes' branch of the diamond, use a parallelogram for 'OUTPUT "High"'.
  6. 6
    1. From the 'No' branch, use a parallelogram for 'OUTPUT "Low"'.
  7. 7
    1. Connect both branches to an 'End' terminator (oval).
  8. 8

    Pseudocode:

  9. 9

    INPUT Number

  10. 10

    IF Number > 10 THEN

  11. 11

    OUTPUT "High"

  12. 12

    ELSE

  13. 13

    OUTPUT "Low"

  14. 14

    ENDIF

Recap

  • Flowcharts are a visual way to design algorithms using standard symbols.
  • Pseudocode uses structured English to describe the steps of an algorithm.
  • The diamond symbol in a flowchart represents a decision (IF statement).
  • The parallelogram symbol represents an input or output.
  • Both tools are used in the Design stage of the PDLC before coding begins.

Quick check

  1. What is the purpose of the oval symbol in a flowchart?1 mark
  2. Should you use Python syntax like `print()` in pseudocode?1 mark

4. Searching Algorithms: Linear Search

A linear search is the simplest way to find an item in a list. It works by starting at the very first item and checking each element one by one, in sequence, until the desired item is found or the end of the list is reached. If the item is found, the search stops and is successful. If the entire list is checked and the item is not present, the search ends unsuccessfully. While easy to implement, it is not very efficient for large lists because, in the worst case, it has to check every single item.

Key term

Linear Search: A searching algorithm that sequentially checks each element of a list until a match is found or the whole list has been searched.

Examiner insight

When explaining a linear search, be sure to mention both the best-case scenario (item is first) and the worst-case scenario (item is last or not present) to show a full understanding.

Worked example 13 marks

Perform a linear search to find the value 18 in the following array: `[10, 25, 4, 18, 3]`. Describe the steps taken. [3]

  1. 1

    Step 1: Compare the target value (18) with the first element (10). They are not a match.

  2. 2

    Step 2: Compare the target value (18) with the second element (25). They are not a match.

  3. 3

    Step 3: Compare the target value (18) with the third element (4). They are not a match.

  4. 4

    Step 4: Compare the target value (18) with the fourth element (18). They are a match. The search stops and reports that the item is found at index 3 (or position 4).

Recap

  • A linear search checks each item in a list sequentially.
  • It starts at the beginning of the list.
  • The search stops as soon as the item is found.
  • If the end of the list is reached, the item is not present.
  • It works on both sorted and unsorted lists.
  • It can be very slow on large lists.

Quick check

  1. What is the best-case scenario for a linear search in a list of 1,000 items?1 mark
  2. What is the maximum number of comparisons needed for a linear search in a list of 1,000 items?1 mark

5. Sorting Algorithms: Bubble Sort

Bubble Sort is a simple sorting algorithm that works by repeatedly stepping through a list, comparing adjacent pairs of elements, and swapping them if they are in the wrong order. This process is repeated in 'passes'. With each pass, the next largest element 'bubbles up' to its correct position at the end of the list. The algorithm continues making passes until a full pass is completed with no swaps, which means the list is now sorted. While simple to understand, it is very inefficient for large lists and is rarely used in real-world applications.

Key term

Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.

Common pitfall

Forgetting that the algorithm requires multiple passes over the list, not just one. A single pass only guarantees that the largest element is moved to the end.

Fun fact

Bubble sort is so inefficient that a programmer at Google once said, 'The only reason to learn bubble sort is to know enough to never, ever use it.'

Worked example 13 marks

Show the state of the list `[6, 2, 5, 1]` after the first full pass of a bubble sort. [3]

  1. 1

    Initial List: `[6, 2, 5, 1]`

  2. 2

    Step 1: Compare 6 and 2. Swap. List becomes `[2, 6, 5, 1]`.

  3. 3

    Step 2: Compare 6 and 5. Swap. List becomes `[2, 5, 6, 1]`.

  4. 4

    Step 3: Compare 6 and 1. Swap. List becomes `[2, 5, 1, 6]`.

  5. 5

    The first pass is complete. The list after the first pass is `[2, 5, 1, 6]`. The largest number, 6, is now at the end.

Recap

  • Bubble sort works by comparing and swapping adjacent elements.
  • It performs multiple passes over the list.
  • After each pass, the next largest element is in its correct final position.
  • The sort is complete when a pass occurs with no swaps.
  • Bubble sort is a very inefficient sorting algorithm for large datasets.

Quick check

  1. After the first pass of a bubble sort on an unsorted list of numbers, which element will be in its final correct position?1 mark

6. Finding Max, Min, and Average

Many algorithms require common calculations like finding the largest (maximum), smallest (minimum), or average value in a list of numbers. These tasks follow standard patterns.

To find the maximum: Initialize a variable `MaxValue` to the first number in the list. Then, loop through the rest of the numbers. If you find a number that is greater than `MaxValue`, update `MaxValue` to this new number. By the end of the loop, `MaxValue` will hold the largest number.

To find the minimum: The logic is identical, but you initialize a `MinValue` and update it whenever you find a smaller number.

To calculate the average: You need two variables: `Total` (initialized to 0) and `Count` (the number of items). Loop through the list, adding each number to `Total`. After the loop, the average is calculated as `Average = Total / Count`.

Average = Total Sum of Values / Number of Values

Key term

Algorithm: A finite sequence of well-defined, computer-implementable instructions, typically to solve a class of problems or to perform a computation.

Worked example 15 marks

Write a pseudocode algorithm that inputs five numbers and outputs the largest number entered. [5]

  1. 1
    1. Initialize a variable to hold the maximum. A good way is to read the first number and set it as the initial maximum.
  2. 2

    `INPUT Number`

  3. 3

    `MaxNumber <- Number`

  4. 4
    1. Loop four more times to get the remaining numbers.
  5. 5

    `FOR Counter <- 1 TO 4`

  6. 6
    1. Inside the loop, get the next number.
  7. 7

    ` INPUT Number`

  8. 8
    1. Compare it with the current maximum and update if necessary.
  9. 9

    ` IF Number > MaxNumber THEN`

  10. 10

    ` MaxNumber <- Number`

  11. 11

    ` ENDIF`

  12. 12

    `NEXT Counter`

  13. 13
    1. After the loop, output the final maximum value.
  14. 14

    `OUTPUT MaxNumber`

Recap

  • To find the maximum, set a variable to the first value, then loop and update if a larger value is found.
  • To find the minimum, set a variable to the first value, then loop and update if a smaller value is found.
  • To find the average, sum all the values in a loop and then divide the total by the count of values.
  • These patterns require initializing a variable before a loop and then updating it inside the loop.

Quick check

  1. To find the average of 20 numbers, what two values do you need to have calculated by the end of your loop?2 marks

7. Ensuring Data Quality: Validation & Verification

It's crucial that data entered into a system is correct. We use two techniques for this: validation and verification.

Validation is an automatic check performed by the computer to ensure that data is sensible, reasonable, and plausible. For example, a program might validate that an age entered is between 0 and 120. It doesn't know if the age is *correct*, only that it's a *possible* age. Common validation checks include range checks, length checks, format checks (e.g., for an email address), and presence checks (ensuring a field isn't left blank).

Verification is a check to ensure that data has been transcribed (e.g., typed in) correctly from a source. It aims to prevent errors during data entry. The most common method is double entry, where the user is asked to type the data (like a new password) twice. If the two entries match, the data is verified.

Key term

Validation: An automatic check by a program to ensure that the data entered is sensible, reasonable, and within acceptable boundaries.

Examiner insight

Marks are often awarded for providing clear examples of each concept. When asked to differentiate, define both terms and then give a distinct example for each.

Common pitfall

Confusing validation and verification. Remember: Validation is an automatic check for 'sensible' data (e.g., age < 120). Verification is a check for 'correctly typed' data (e.g., re-enter password).

Worked example 14 marks

A website form asks for a username which must be between 6 and 15 characters long. It also asks the user to create and then confirm a new password. Explain how validation and verification are used here. [4]

  1. 1

    Validation: The system performs a length check on the username to ensure it is between 6 and 15 characters. This is an automatic check for sensibility. [2]

  2. 2

    Verification: The system asks the user to enter the password twice (double entry). It then compares the two entries to ensure they match, verifying that the password was typed correctly without typos. [2]

Recap

  • Validation is an automated check to ensure data is sensible and reasonable.
  • Examples of validation include range, length, and format checks.
  • Verification is a check to ensure data has been entered correctly, preventing transcription errors.
  • The most common verification method is double entry.
  • Validation checks if data is plausible, while verification checks if it was typed correctly.

Quick check

  1. A program rejects a date of '30/02/2023'. Is this validation or verification?1 mark

8. Tracing and Debugging Algorithms

An algorithm can have 'bugs' or errors. Logic errors are particularly tricky because the program runs but produces the wrong result. A trace table is a vital tool for finding these errors. It's a table where you manually track the values of variables as the computer would execute the algorithm, line by line. Each column in the table represents a variable, and each row represents a step in the algorithm. By carefully tracing the execution, you can see where the logic goes wrong.

Once you've traced an algorithm, you can better explain its purpose. Instead of just saying 'Line 1 inputs a number, Line 2 starts a loop', you should synthesize what you've learned from the trace to describe the overall goal, for example: 'The algorithm calculates the sum of 10 numbers entered by the user.'

Key term

Trace Table: A technique used to test algorithms by tracking the values of variables at each step of the execution to understand its behaviour and find errors.

Examiner insight

When asked to complete a trace table, be meticulous. A single incorrect value can cause you to lose all subsequent marks for that variable's column. Work carefully, one step at a time.

Worked example 15 marks

Complete the trace table for the following pseudocode algorithm when the user inputs the value 4.

PSEUDOCODE: 01 INPUT N 02 Total <- 1 03 FOR I <- 1 TO N 04 Total <- Total * I 05 NEXT I 06 OUTPUT Total

TRACE TABLE:

LineNITotalOutput
014??
024?1
...
  1. 1

    The goal is to track N, I, and Total as the loop runs from 1 to 4.

  2. 2

    Initial State: N=4, Total=1.

  3. 3

    Loop 1 (I=1): Total becomes 1 * 1 = 1.

  4. 4

    Loop 2 (I=2): Total becomes 1 * 2 = 2.

  5. 5

    Loop 3 (I=3): Total becomes 2 * 3 = 6.

  6. 6

    Loop 4 (I=4): Total becomes 6 * 4 = 24.

  7. 7

    After loop: The algorithm outputs the final value of Total.

  8. 8

    Completed Trace Table:

  9. 9

    | Line | N | I | Total | Output |

  10. 10
  11. 11

    | 01 | 4 | - | - | |

  12. 12

    | 02 | 4 | - | 1 | |

  13. 13

    | 03 | 4 | 1 | 1 | |

  14. 14

    | 04 | 4 | 1 | 1 | |

  15. 15

    | 03 | 4 | 2 | 1 | |

  16. 16

    | 04 | 4 | 2 | 2 | |

  17. 17

    | 03 | 4 | 3 | 2 | |

  18. 18

    | 04 | 4 | 3 | 6 | |

  19. 19

    | 03 | 4 | 4 | 6 | |

  20. 20

    | 04 | 4 | 4 | 24 | |

  21. 21

    | 06 | 4 | 4 | 24 | 24 |

Recap

  • A trace table is used to manually execute an algorithm on paper.
  • It helps find logic errors by tracking variable values.
  • Each variable gets its own column in the table.
  • A new row is added for each change in a variable's value.
  • Tracing helps you understand an algorithm's overall purpose.

Quick check

  1. What type of programming error is a trace table most useful for finding?1 mark

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. Define the term 'algorithm' and explain the purpose of 'decomposition'. [3]3 marks
  2. Describe the 'Analysis' and 'Design' stages of the Program Development Life Cycle. [4]4 marks
  3. Draw a flowchart for an algorithm that asks for a user's age and outputs 'Child' if they are under 13, 'Teenager' if they are 13-19, and 'Adult' otherwise. [6]6 marks
  4. A program requires a user to enter an exam score, which must be an integer between 0 and 100 inclusive. Identify one piece of normal, one piece of boundary, and one piece of erroneous test data for this input. [3]3 marks
  5. Show the state of the list `[9, 5, 1, 7]` after each individual swap during the first full pass of a bubble sort. [4]4 marks
  6. Write a pseudocode algorithm that will repeatedly ask the user to enter a positive number until they enter -1. The algorithm should then output the average of all the positive numbers entered. [6]6 marks
  7. Explain the difference between validation and verification, using a clear example for each related to signing up for a new online account. [4]4 marks
  8. Complete a trace table for the following algorithm, assuming the input is `[5, 8, 2, 9]`. The algorithm reads one number per loop iteration. `Min <- 100` `FOR i <- 1 TO 4` ` INPUT Num` ` IF Num < Min THEN` ` Min <- Num` ` ENDIF` `NEXT i` `OUTPUT Min` [5]5 marks
  9. The following algorithm is intended to calculate the sum of 5 numbers. It contains a logic error. Identify the error and write the corrected line of code. `Total <- 100` `FOR C <- 1 TO 5` ` INPUT Number` ` Total <- Total + Number` `NEXT C` `OUTPUT Total` [2]2 marks
  10. Describe the overall purpose of the following pseudocode algorithm. Do not give a line-by-line description. `Count <- 0` `INPUT X` `WHILE X > 0 DO` ` X <- X - 2` ` Count <- Count + 1` `ENDWHILE` `OUTPUT Count` [3]3 marks

Go deeper

Practise and revise with member-only material for this chapter.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters