Study Notes: Topic 4 - Algorithms and Flowcharts (9626 AS Level)
Hello future IT expert! This chapter is where we learn the language of problem-solving. Whether you are building a vast corporate system or just deciding what to eat for dinner, you follow a set of steps. In computing, these steps are called algorithms.
Understanding algorithms and flowcharts is fundamental. They form the blueprint for every piece of software ever written. Master this, and you’ve mastered the core logic of programming!
Quick Review: Why do we need algorithms?
- To provide a clear, unambiguous sequence of steps to solve a specific problem.
- To allow programmers to design the logic before writing code (saving time and money).
- To ensure the solution is logical and can be understood and maintained by others.
4.1 Algorithms: The Instruction Manual
An Algorithm is a set of finite, well-defined, step-by-step procedures for accomplishing a task. Think of it as a recipe for a computer.
In exams, you will be expected to write algorithms using structured English known as Pseudocode.
4.1.1 Basic Input and Output
These commands handle how data enters and leaves the system.
-
INPUT/READ: Gets data from the user or a file.
Example:
INPUT UserName -
WRITE/PRINT: Displays or outputs data (to the screen, printer, or a file).
Example:
WRITE "Welcome, " & UserName
4.1.2 Arithmetic Operations
Algorithms use standard arithmetic operators to perform calculations:
- Addition: \(+\)
- Subtraction: \(-\)
- Multiplication: \(*\)
- Division: \(/ \)
Example:
TotalCost = Quantity * Price
4.1.3 Selection (Decision Making)
Selection allows the algorithm to choose between different paths based on a condition. This is known as conditional branching.
IF...ELSE...ENDIF Structure
This is used when there are one or two possible paths.
Structure:
IF (condition is true) THEN
// Do this action
ELSE
// Do the other action
ENDIF
Example (Checking age):
INPUT Age
IF Age >= 18 THEN
WRITE "Access granted"
ELSE
WRITE "Access denied"
ENDIF
Comparison Operators are essential for conditions:
\(>\) (Greater than), \(<\) (Less than), \(=\) (Equal to), \(\neq\) (Not equal to), \(\ge\) (Greater than or equal to), \(\le\) (Less than or equal to).
CASE...ENDCASE Structure
This is used when you have multiple choices based on the value of a single variable. This is cleaner than using lots of nested IF statements.
Structure:
CASE OF Variable
Value 1: // Action for Value 1
Value 2: // Action for Value 2
OTHERWISE: // Action if none match
ENDCASE
4.1.4 Iteration (Looping)
Iteration, or looping, is the process of repeating a block of code multiple times.
FOR...NEXT Loop
Used when you know exactly how many times the loop needs to run (a definite number of iterations).
Structure:
FOR Counter = StartValue TO EndValue [STEP Increment]
// Loop actions
NEXT Counter
Example (Counting down):
FOR i = 10 TO 1 STEP -1
WRITE i
NEXT i
Did you know? If you omit STEP Increment, the step defaults to 1.
WHILE...ENDWHILE Loop
This is a pre-condition loop: the condition is checked before the loop runs the first time. If the condition is false initially, the loop will never execute.
Structure:
WHILE (condition is true)
// Loop actions
ENDWHILE
Analogy: You check the weather (condition) before leaving the house. If it’s sunny, you don’t take an umbrella (loop actions).
REPEAT...UNTIL Loop
This is a post-condition loop: the loop actions execute at least once, and the condition is checked after the execution. The loop continues UNTIL the condition becomes true.
Structure:
REPEAT
// Loop actions (will run at least once)
UNTIL (condition is true)
Analogy: You try opening a tricky jar (loop action) and keep trying (repeat) UNTIL the lid comes off (condition true).
Nested Loops
A nested loop is a loop inside another loop. This is essential for tasks like processing data in tables (rows and columns).
Crucial Tip: The inner loop must complete all its iterations before the outer loop can proceed to its next iteration. Always use different counter variables (e.g., use i for the outer loop and j for the inner loop).
4.1.5 Procedures and Subroutines
A procedure (or subroutine) is a self-contained block of code designed to perform a specific task.
- They help break down complex programs into smaller, manageable chunks (modularity).
- They allow the code to be reused easily without rewriting it.
In pseudocode, you would define or declare the subroutine and then call it later:
Example:
PROCEDURE Calculate_Tax (Salary)
Tax = Salary * 0.20
WRITE Tax
ENDPROCEDURE
Calling the subroutine:
CALL Calculate_Tax (50000)
Quick Review: Pseudocode Structures
- Selection: Chooses a path (IF/ELSE or CASE).
- Iteration: Repeats actions (FOR, WHILE, REPEAT).
- Procedures: Organises and reuses blocks of code.
Memory Aid: Remember the types of loops based on the check: WHILE checks Whole time (pre-condition), REPEAT checks Rear (post-condition).
4.2 Flowcharts: The Visual Map
A Flowchart is a diagrammatic representation of an algorithm. It uses standard symbols to illustrate the sequence of operations to be performed to get the solution.
Flowcharts are great for struggling students because they provide a visual way to track the program's logic and identify potential errors easily.
4.2.1 Standard Flowchart Symbols
You must know the shape, name, and function of these standard symbols (as provided in the syllabus):
| Symbol Name | Shape (Description) | Function / Use |
|---|---|---|
| Terminator (Start/Stop) | Oval / Rounded Rectangle | Indicates the beginning or end of the program/algorithm. |
| Input/Output | Parallelogram | Used for any data input (READ, INPUT) or data output (WRITE, PRINT). |
| Process Box | Rectangle | Indicates any processing or calculation step (e.g., assigning values, arithmetic operations). |
| Decision | Diamond | Represents a decision or conditional test (IF...THEN). It must have one incoming flowline and two outgoing flowlines (usually labelled YES/NO or TRUE/FALSE). |
| Subroutine | Rectangle with double vertical lines | Represents a call to a separate, defined procedure or subroutine. |
| Connector | Circle (often containing a letter/number) | Used to indicate that the flowchart continues to another location on the same page. Avoids crossing flowlines. |
| Flowline | Arrow | Shows the direction and sequence of control within the flowchart. |
4.2.2 Drawing a Flowchart: Step-by-Step
Let’s represent the conditional branching structure (IF...ELSE...ENDIF) for checking a user's age:
- Start: Begin with the Terminator symbol, labelled START.
- Input: Use the Input/Output parallelogram to get the age: INPUT Age.
- Decision: Use the Decision diamond to check the condition: Age >= 18?
- Processing Paths:
- If YES (True): Follow the flowline to an Input/Output parallelogram: WRITE "Access granted".
- If NO (False): Follow the other flowline to an Input/Output parallelogram: WRITE "Access denied".
- Merge and End: Join the two resulting flowlines back together using a Connector if necessary, or simply merge them before flowing into the final Terminator symbol, labelled STOP.
(Note: Since direct image rendering is not possible in this HTML format, visualize the shapes above following these steps!)
4.2.3 Representing Loops in Flowcharts
All iterative structures (FOR, WHILE, REPEAT) are primarily represented using the Decision diamond and flowlines that loop back up the chart.
- WHILE Loop: The Decision diamond must appear before the process box, controlling entry into the loop body.
- REPEAT Loop: The Decision diamond appears after the process box, ensuring the loop executes once before the condition is checked.
Editing and Identifying Errors
A key skill is being able to spot mistakes, whether in pseudocode or a flowchart.
4.3.1 Common Algorithm Errors to Avoid
-
Infinite Loops: This happens when a loop’s stopping condition can never be met.
Mistake: A WHILE loop that never updates the variable used in its condition (e.g.,
WHILE Count < 10butCountis never incremented). -
Incorrect Looping Bounds: Using
<instead of<=, or starting the counter at 0 when it should start at 1. Always check if the loop runs the correct number of times. -
Incorrect Branching Logic: Using the wrong comparison operator (e.g., using
>when you meant>=), which causes the algorithm to take the wrong path for boundary cases. -
Syntax Errors in Pseudocode: Mismatching keywords (e.g., starting with
IFbut ending withNEXT, or forgettingENDIF).
4.3.2 Identifying Errors in Flowcharts
When examining a flowchart, look for:
- Disconnected Symbols: Is every symbol linked by a flowline?
- Invalid Decision Outputs: Does the Decision diamond (rhombus) have exactly two clearly labelled exit paths (e.g., T/F or Y/N)?
- Incorrect Symbol Use: Is a Process box being used for input, or an Input/Output box being used for calculation?
- Loop Direction: For repetition, do the flowlines correctly loop back to the decision point?
Don't worry if identifying errors seems tricky at first! This skill improves with practice. The best way to check is to trace the algorithm with simple test data and see if it behaves as intended.
Key Takeaway
Algorithms are the descriptive steps written in pseudocode, focusing on clarity and structured logic (Selection, Iteration, Procedures). Flowcharts are the visual diagram, using standard symbols to map the flow and sequence of the algorithm. Both must accurately reflect the problem being solved.