Cambridge AS & A Level9608

Algorithm design and problem-solving

Computer Science 9608 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.

~18 min read

1. What is an Algorithm?

An algorithm is a precise, step-by-step set of instructions designed to solve a specific problem or perform a task. Think of it as a recipe for a computer. For an algorithm to be useful, its steps must be unambiguous and finite, meaning it must eventually stop. Most simple algorithms follow a basic Input-Process-Output (IPO) model: they take some data as input, perform some operations on it (the process), and then produce a result (the output).

Key term

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

Examiner insight

Examiners reward clear, logical thinking that shows an understanding of breaking a problem down into discrete, ordered steps.

Common pitfall

Thinking an algorithm has to be written in code; it's a plan that can be expressed in many ways, including plain English or diagrams.

Fun fact

The word 'algorithm' is derived from the name of the 9th-century Persian mathematician, Muhammad ibn Musa al-Khwarizmi.

Worked example 13 marks

An algorithm is needed to calculate the area of a rectangle. Describe this algorithm using the Input-Process-Output (IPO) model.

  1. 1

    Step 1: Identify the inputs. To calculate the area of a rectangle, we need its length and width. Input: Length, Width.

  2. 2

    Step 2: Define the process. The area is calculated by multiplying the length and the width. Process: Area = Length * Width.

  3. 3

    Step 3: Determine the output. The result of the calculation is the area. Output: Area.

Recap

  • An algorithm is a step-by-step plan to solve a problem.
  • Algorithms must be clear, unambiguous, and have a defined end point.
  • The Input-Process-Output (IPO) model describes how an algorithm takes data, manipulates it, and produces a result.
  • A good algorithm is correct, efficient, and easy to understand.

Quick check

  1. For an algorithm that converts a temperature from Celsius to Fahrenheit, what is the input, process, and output?3 marks

2. Documenting Algorithms: Pseudocode & Flowcharts

To communicate algorithms clearly, we use standardised methods. Structured English uses a limited vocabulary of English commands. Pseudocode is more formal, using keywords and indentation to resemble a programming language but without being tied to one specific language's strict syntax. It's the most common method in exams. A Program Flowchart is a graphical representation using standard symbols to show the flow of control. Ovals represent start/end points, parallelograms for input/output, rectangles for processes, and diamonds for decisions.

Key term

Pseudocode: A plain language description of the steps in an algorithm, using structured conventions (like keywords and indentation) for clarity.

Examiner insight

Marks are often awarded for using standard conventions correctly, such as using a diamond for decisions in flowcharts or the `←` symbol for assignment in pseudocode.

Common pitfall

Mixing up flowchart symbols, for example using a rectangle (process) for input/output instead of a parallelogram.

Worked example 16 marks

An algorithm reads a user's age. If the age is 18 or over, it prints 'Access granted'. Otherwise, it prints 'Access denied'. Represent this algorithm using both pseudocode and a program flowchart.

  1. 1

    Pseudocode Solution:

  2. 2

    INPUT Age

  3. 3

    IF Age >= 18 THEN

  4. 4

    OUTPUT "Access granted"

  5. 5

    ELSE

  6. 6

    OUTPUT "Access denied"

  7. 7

    ENDIF

  8. 8

    Flowchart Solution:

  9. 9
    1. Start with a 'Start' terminator (oval).
  10. 10
    1. Use an input symbol (parallelogram) with the text 'Input Age'.
  11. 11
    1. Use a decision symbol (diamond) with the condition 'Age >= 18?'.
  12. 12
    1. From the 'Yes' branch of the diamond, draw a flow line to an output symbol (parallelogram) with 'Output "Access granted"'.
  13. 13
    1. From the 'No' branch of the diamond, draw a flow line to an output symbol (parallelogram) with 'Output "Access denied"'.
  14. 14
    1. Draw flow lines from both output symbols to an 'End' terminator (oval).

Recap

  • Algorithms can be documented using structured English, pseudocode, or flowcharts.
  • Pseudocode uses keywords like INPUT, OUTPUT, IF...THEN...ELSE, and REPEAT...UNTIL.
  • Flowcharts use standard symbols for start/end, process, input/output, and decision.
  • The diamond symbol in a flowchart always represents a decision (a question with a yes/no answer).
  • Pseudocode is the most common format required in Cambridge examinations.

Quick check

  1. What shape is used in a flowchart to represent a process or an instruction?1 mark
  2. What pseudocode keyword is used to get data from a user?1 mark

3. The Four Basic Algorithm Constructs

All algorithms, no matter how complex, are built from four basic constructs.

  1. Assignment: Giving a value to an identifier (variable). E.g., `Score ← 0` or `Name ← "Alice"`.
  2. Sequence: A series of instructions that are executed one after another in the order they are written.
  3. Selection: A choice point where the algorithm follows a different path based on a condition. This is implemented using `IF...THEN...ELSE...ENDIF`.
  4. Repetition (or Iteration): Repeating a block of instructions. This can be a count-controlled loop (`FOR...TO...NEXT`), a pre-condition loop (`WHILE...ENDWHILE`), or a post-condition loop (`REPEAT...UNTIL`).

Key term

Selection: A control structure that allows a choice to be made between different paths of execution based on a condition.

Examiner insight

Correctly nesting constructs, such as an `IF` statement inside a `FOR` loop, demonstrates a higher level of algorithmic thinking and is often required for top marks.

Common pitfall

Forgetting to include the closing keyword for a construct, such as `ENDIF` for an `IF` statement or `ENDWHILE` for a `WHILE` loop.

Worked example 17 marks

Write a pseudocode algorithm that asks the user to enter 10 positive numbers. The algorithm should calculate and output the sum of these numbers. It should ignore any negative numbers entered.

  1. 1

    Step 1: Initialise a variable to hold the sum and a counter for the loop. This is Assignment. `Total ← 0`

  2. 2

    Step 2: Set up a loop to repeat 10 times. This is Repetition. `FOR Counter ← 1 TO 10`

  3. 3

    Step 3: Inside the loop, get a number from the user. This is part of the Sequence. `INPUT Number`

  4. 4

    Step 4: Check if the number is positive. This is Selection. `IF Number > 0 THEN`

  5. 5

    Step 5: If it is positive, add it to the total. This is Assignment and part of the Sequence inside the selection. `Total ← Total + Number`

  6. 6

    Step 6: Close the selection and the loop. `ENDIF`, `NEXT Counter`

  7. 7

    Step 7: After the loop, output the final result. `OUTPUT "The total is: ", Total`

  8. 8

    Full Pseudocode:

  9. 9

    Total ← 0

  10. 10

    FOR Counter ← 1 TO 10

  11. 11

    OUTPUT "Enter a positive number: "

  12. 12

    INPUT Number

  13. 13

    IF Number > 0 THEN

  14. 14

    Total ← Total + Number

  15. 15

    ENDIF

  16. 16

    NEXT Counter

  17. 17

    OUTPUT "The total of positive numbers is: ", Total

Recap

  • Assignment gives a value to an identifier, e.g., `MyScore ← 100`.
  • Sequence is the execution of steps in the order they are written.
  • Selection uses IF statements to make decisions and choose a path.
  • Repetition uses loops (FOR, WHILE, REPEAT) to execute statements multiple times.

Quick check

  1. Which construct would you use to check if a user is old enough to vote?1 mark
  2. Which construct would you use to process every student in a class list of 30 students?1 mark

4. Identifiers and Identifier Tables

An identifier is the name we give to a variable, constant, or procedure in an algorithm. It's crucial to choose meaningful identifiers (e.g., `StudentName` instead of `S`) to make algorithms readable and easier to debug. Before writing an algorithm, it's good practice to create an identifier table. This table lists all the identifiers you plan to use, their data type (e.g., Integer, String, Boolean), and a short description of their purpose. This helps you plan your solution and serves as documentation.

Key term

Identifier: A name given to an element in a program, such as a variable, constant, or procedure, to uniquely identify it.

Examiner insight

Creating a clear identifier table before writing the main algorithm can earn marks on its own and also helps to structure your thinking, reducing errors in the main part of the question.

Common pitfall

Using generic, single-letter identifiers like 'x' or 'a' which make the algorithm's purpose difficult to understand for others (and for yourself later).

Worked example 15 marks

An algorithm is required to calculate the total cost for a number of cinema tickets. The user inputs the number of adult tickets and child tickets. An adult ticket costs $12.50 and a child ticket costs $7.00. Create an identifier table for this problem.

  1. 1

    Step 1: Identify all the data items needed. We need the number of adults, number of children, the cost of an adult ticket, the cost of a child ticket, and the final total cost.

  2. 2

    Step 2: Choose meaningful names for each item.

  3. 3

    Step 3: Determine the data type for each item (e.g., numbers for counting are integers, costs with decimals are real/currency).

  4. 4

    Step 4: Write a brief description of each identifier's purpose.

  5. 5

    Identifier Table:

  6. 6

    | Identifier Name | Data Type | Description |

  7. 7
  8. 8

    | NumAdults | Integer | Stores the number of adult tickets input by the user. |

  9. 9

    | NumChildren | Integer | Stores the number of child tickets input by the user. |

  10. 10

    | ADULT_COST | Real / Currency | A constant holding the price of one adult ticket ($12.50). |

  11. 11

    | CHILD_COST | Real / Currency | A constant holding the price of one child ticket ($7.00). |

  12. 12

    | TotalCost | Real / Currency | Stores the calculated total cost for all tickets. |

Recap

  • An identifier is a name for a variable, constant or procedure.
  • Identifiers should be meaningful to improve the readability of the algorithm.
  • An identifier table documents the name, data type, and purpose of each identifier.
  • Planning with an identifier table can prevent errors and clarify your logic.

Quick check

  1. Suggest a suitable identifier and data type for storing a student's exam percentage.2 marks

5. Using Logic in Algorithms

Logic is the heart of decision-making in algorithms. Selection and repetition constructs rely on conditions, which are expressions that evaluate to either TRUE or FALSE (Boolean values). These conditions are built using relational operators to compare values (`=`, `<>`, `>`, `<`, `>=`, `<=`) and logical operators to combine conditions (`AND`, `OR`, `NOT`). For example, `IF Age >= 18 AND HasID = TRUE` combines two checks. The `AND` means both must be true for the whole condition to be true. `OR` means only one needs to be true. `NOT` reverses the truth value of a condition.

Relational Operators: =, <>, <, >, <=, >=

Logical Operators: AND, OR, NOT

Key term

Boolean Expression: An expression that results in a Boolean value, that is, in a value of either TRUE or FALSE.

Examiner insight

Examiners look for the correct use of brackets to ensure logical expressions are evaluated in the intended order, especially with complex combinations of AND and OR.

Common pitfall

Confusing the assignment operator (`←`) with the equality comparison operator (`=`). In Cambridge pseudocode, `←` is for assignment and `=` is for comparison.

Worked example 12 marks

A theme park gives a discount if a person is either under 12 years old or over 65 years old. Write the pseudocode for a logical expression that would be TRUE if a person with age `Age` qualifies for the discount.

  1. 1

    Step 1: Identify the two separate conditions for a discount. The first is being under 12. The second is being over 65.

  2. 2

    Step 2: Translate the first condition into a relational expression: `Age < 12`.

  3. 3

    Step 3: Translate the second condition into a relational expression: `Age > 65`.

  4. 4

    Step 4: The problem states the discount applies if *either* condition is met. The logical operator for this is `OR`.

  5. 5

    Step 5: Combine the expressions with the OR operator: `(Age < 12) OR (Age > 65)`.

  6. 6

    Note: The brackets are used for clarity but are not strictly necessary here due to operator precedence.

Worked example 23 marks

A program needs to validate a user's chosen password. The password is valid if it is at least 8 characters long AND contains the '@' symbol. The length is stored in `PasswordLength` and a boolean `HasAtSymbol` is TRUE if it contains the symbol. Write the pseudocode `IF` statement.

  1. 1

    Step 1: Identify the two conditions for a valid password.

  2. 2

    Step 2: The first condition is that the length is at least 8: `PasswordLength >= 8`.

  3. 3

    Step 3: The second condition is that it contains the '@' symbol: `HasAtSymbol = TRUE`.

  4. 4

    Step 4: The problem states *both* conditions must be met, so use the `AND` operator.

  5. 5

    Step 5: Combine them into a full IF statement: `IF (PasswordLength >= 8) AND (HasAtSymbol = TRUE) THEN ...`

Recap

  • Relational operators (<, >, =, etc.) are used to compare two values.
  • Logical operators (AND, OR, NOT) are used to combine or modify Boolean conditions.
  • AND requires all connected conditions to be TRUE.
  • OR requires only one of the connected conditions to be TRUE.
  • NOT reverses a condition from TRUE to FALSE, or FALSE to TRUE.
  • These logical expressions control the flow of selection and repetition constructs.

Quick check

  1. Write a logical expression that is TRUE if a variable `x` is not equal to 10.1 mark

6. Working with Arrays

An array is a data structure used to store a collection of related data items, all of the same data type, under a single identifier. Each item, or element, in the array is accessed by its position, called an index. A one-dimensional (1D) array is like a list. The first index is the 'lower bound' and the last is the 'upper bound'. For example, `Scores : ARRAY[1:30] OF INTEGER` declares an array to hold 30 integer scores. A two-dimensional (2D) array is like a table or grid, using two indices (row and column) to access an element, e.g., `ChessBoard : ARRAY[1:8, 1:8] OF STRING`.

1D Array Declaration: DECLARE <Identifier> : ARRAY[<Lower>:<Upper>] OF <DataType>

2D Array Declaration: DECLARE <Identifier> : ARRAY[<L1>:<U1>, <L2>:<U2>] OF <DataType>

Key term

Array: A data structure consisting of a collection of elements of the same data type, each identified by at least one array index.

Examiner insight

Demonstrating the ability to loop through an array using its lower and upper bounds to access each element is a fundamental skill tested frequently.

Common pitfall

An 'off-by-one' error, where a loop runs one time too many or too few, often by mixing up array bounds. For an array `A[1:10]`, the loop should be `FOR i ← 1 TO 10`.

Worked example 16 marks

An array, `TestScores`, is used to store the scores of 5 students. The scores are 88, 92, 75, 100, 84. Write pseudocode to declare this array, assign the values, and then calculate and output the average score.

  1. 1

    Step 1: Declare a 1D array to hold 5 integer scores. `DECLARE TestScores : ARRAY[1:5] OF INTEGER`.

  2. 2

    Step 2: Assign the given scores to the array elements. `TestScores[1] ← 88`, `TestScores[2] ← 92`, etc.

  3. 3

    Step 3: Initialise a variable for the sum. `Total ← 0`.

  4. 4

    Step 4: Loop through the array from the lower bound to the upper bound. `FOR Index ← 1 TO 5`.

  5. 5

    Step 5: Inside the loop, add the current element's value to the total. `Total ← Total + TestScores[Index]`.

  6. 6

    Step 6: After the loop, calculate the average. `Average ← Total / 5`.

  7. 7

    Step 7: Output the result. `OUTPUT "The average score is: ", Average`.

  8. 8

    Full Pseudocode:

  9. 9

    DECLARE TestScores : ARRAY[1:5] OF INTEGER

  10. 10

    DECLARE Total : INTEGER

  11. 11

    DECLARE Average : REAL

  12. 12

    TestScores[1] ← 88; TestScores[2] ← 92; TestScores[3] ← 75; TestScores[4] ← 100; TestScores[5] ← 84

  13. 13

    Total ← 0

  14. 14

    FOR Index ← 1 TO 5

  15. 15

    Total ← Total + TestScores[Index]

  16. 16

    NEXT Index

  17. 17

    Average ← Total / 5

  18. 18

    OUTPUT "The average score is: ", Average

Recap

  • An array stores multiple values of the same data type.
  • A 1D array is a list, a 2D array is a table.
  • Each element in an array is accessed using its index.
  • The 'lower bound' is the first index and the 'upper bound' is the last.
  • Loops are essential for processing all elements in an array.

Quick check

  1. Write the pseudocode to declare a 1D array named `Months` to store the 12 months of the year as strings.2 marks

7. Searching Arrays: Linear Search

A linear search is the simplest method for finding an item in an array. It works by starting at the first element (the lower bound) and checking each element sequentially until either the desired item is found, or the end of the array is reached. Because it checks every element, it works on both sorted and unsorted arrays. While simple to implement, it can be inefficient for very large arrays.

Key term

Linear Search: A search algorithm that finds the position of a target value within a list by sequentially checking each element until a match is found or the list is fully traversed.

Examiner insight

A good answer will not only find the item but also correctly handle the case where the item is not present in the array, typically using a Boolean flag.

Common pitfall

Writing a loop that finds the item, but failing to correctly report that the item was *not* found if the loop finishes without a match.

Worked example 18 marks

An array `Names` of size 100 stores a list of names. Write a pseudocode algorithm to perform a linear search for a `SearchName` provided by the user. The algorithm should output the array index (position) if the name is found, or 'Name not found' if it is not.

  1. 1

    Step 1: Get the name to search for from the user. `INPUT SearchName`.

  2. 2

    Step 2: Use a flag variable to track if the name has been found. Initialise it to false. `Found ← FALSE`.

  3. 3

    Step 3: Use a counter or index variable for the loop, starting at the lower bound. `Position ← 1`.

  4. 4

    Step 4: Set up a loop that continues as long as the name isn't found and the end of the array hasn't been reached. `WHILE Found = FALSE AND Position <= 100`.

  5. 5

    Step 5: Inside the loop, compare the current array element with the search name. `IF Names[Position] = SearchName THEN`.

  6. 6

    Step 6: If they match, set the flag to true. `Found ← TRUE`.

  7. 7

    Step 7: If they don't match, move to the next position. `ELSE Position ← Position + 1`.

  8. 8

    Step 8: After the loop, check the flag. If it's true, the name was found at the current `Position`. If false, it was never found.

  9. 9

    Full Pseudocode:

  10. 10

    DECLARE Names : ARRAY[1:100] OF STRING

  11. 11

    DECLARE SearchName : STRING

  12. 12

    DECLARE Found : BOOLEAN

  13. 13

    DECLARE Position : INTEGER

  14. 14

    // Assume array 'Names' is already populated

  15. 15

    INPUT SearchName

  16. 16

    Found ← FALSE

  17. 17

    Position ← 1

  18. 18

    WHILE Found = FALSE AND Position <= 100

  19. 19

    IF Names[Position] = SearchName THEN

  20. 20

    Found ← TRUE

  21. 21

    ELSE

  22. 22

    Position ← Position + 1

  23. 23

    ENDIF

  24. 24

    ENDWHILE

  25. 25

    IF Found = TRUE THEN

  26. 26

    OUTPUT "Name found at position: ", Position

  27. 27

    ELSE

  28. 28

    OUTPUT "Name not found"

  29. 29

    ENDIF

Recap

  • A linear search checks each element of an array one by one.
  • It starts at the beginning and stops when the item is found or the end is reached.
  • Linear search works on both sorted and unsorted arrays.
  • It is simple to write but can be slow for very large arrays.

Quick check

  1. In the worst-case scenario, how many comparisons are needed to find an item in an array of 500 elements using a linear search?1 mark

8. Sorting Arrays: Bubble Sort

Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the array, comparing each pair of adjacent items, and swapping them if they are in the wrong order. This process is repeated in multiple 'passes'. With each pass, the next largest element 'bubbles' up to its correct position at the end of the array. The algorithm can stop when a full pass is completed with no swaps being made, as this indicates the array is fully sorted.

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.

Examiner insight

Full marks for a bubble sort algorithm are typically awarded for solutions that are efficient. An optimised version uses a flag to detect if any swaps were made during a pass; if no swaps occur, the array is sorted and the algorithm can stop early.

Common pitfall

Making errors in the swap logic (e.g., `A = B; B = A;` which loses the original value of A) instead of correctly using a temporary variable.

Worked example 17 marks

Write a pseudocode algorithm to sort a 1D integer array named `Numbers` of size `N` into ascending order using the bubble sort algorithm.

  1. 1

    Step 1: The basic idea is to have nested loops. The outer loop controls the number of passes, and the inner loop performs the adjacent comparisons and swaps.

  2. 2

    Step 2: The outer loop will run from the end of the array down to the second element. This defines the 'unsorted' part of the array. `FOR Pass ← N-1 DOWNTO 1`.

  3. 3

    Step 3: The inner loop will go from the start of the array up to the boundary defined by the outer loop. `FOR Index ← 1 TO Pass`.

  4. 4

    Step 4: Inside the inner loop, compare the current element with the next one. `IF Numbers[Index] > Numbers[Index+1] THEN`.

  5. 5

    Step 5: If they are in the wrong order, swap them. This requires a temporary variable. `Temp ← Numbers[Index]`, `Numbers[Index] ← Numbers[Index+1]`, `Numbers[Index+1] ← Temp`.

  6. 6

    Step 6: Close all loops and conditions.

  7. 7

    Full Pseudocode:

  8. 8

    DECLARE Numbers : ARRAY[1:N] OF INTEGER

  9. 9

    DECLARE Temp : INTEGER

  10. 10

    FOR Pass ← 1 TO N-1

  11. 11

    FOR Index ← 1 TO N-Pass

  12. 12

    IF Numbers[Index] > Numbers[Index+1] THEN

  13. 13

    Temp ← Numbers[Index]

  14. 14

    Numbers[Index] ← Numbers[Index+1]

  15. 15

    Numbers[Index+1] ← Temp

  16. 16

    ENDIF

  17. 17

    NEXT Index

  18. 18

    NEXT Pass

Recap

  • Bubble sort repeatedly compares and swaps adjacent elements.
  • With each pass, the largest unsorted element moves to its final position.
  • The algorithm requires nested loops to implement.
  • A temporary variable is needed to perform the swap.
  • Bubble sort is simple but not efficient for large datasets.

Quick check

  1. When sorting an array into ascending order, what does a bubble sort algorithm do if it finds two adjacent elements `A` and `B` where `A > B`?1 mark

End-of-chapter exercise

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

  1. Define the term 'algorithm' and name two different methods used to represent an algorithm.3 marks
  2. Create an identifier table for an algorithm that calculates a user's age in days. The algorithm will input their age in years.3 marks
  3. Draw a program flowchart for an algorithm that inputs two numbers and outputs the larger of the two.4 marks
  4. Write a pseudocode algorithm that repeatedly asks a user to enter a number until they enter a value between 1 and 100 inclusive.4 marks
  5. A student gets a distinction if their `Mark` is over 80 and they have completed all `Coursework`. Write a single logical expression in a pseudocode IF statement that would be TRUE if a student achieves a distinction.3 marks
  6. An array `StudentNames` is declared as `DECLARE StudentNames : ARRAY[1:35] OF STRING`. What are the upper and lower bounds of this array? Write a pseudocode loop to output all the names stored in the array.4 marks
  7. A 2D array, `GameBoard : ARRAY[1:10, 1:10] OF CHAR`, is used to represent a game. An empty square is marked with 'E'. Write a pseudocode algorithm to count and output the number of empty squares on the board.5 marks
  8. Write a pseudocode algorithm to perform a linear search on an array of 50 strings called `Products` to find a `SearchItem` input by the user. The algorithm should output the index of the item if found, or "Item not found" otherwise.6 marks
  9. The following integer array needs to be sorted into ascending order: `[9, 5, 2, 7, 4]`. Show the state of the array after the completion of each pass of a bubble sort algorithm.4 marks
  10. Convert the following pseudocode, which determines a discount based on an `Amount`, into a program flowchart. INPUT Amount IF Amount > 1000 THEN Discount ← 0.2 ELSE Discount ← 0.1 ENDIF Price ← Amount * (1 - Discount) OUTPUT Price5 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