1 - Fundamentals of Algorithms
1 - Fundamentals of Algorithms
1. What is an Algorithm?
An algorithm is a step-by-step set of instructions to solve a problem or perform a task. Think of it as a
recipe: you follow the steps in order to get the final dish.
Flowcharts:
Flowcharts are a way to visually represent the steps in an algorithm. They use different shapes to
represent different types of actions, and arrows to show the flow of control between these actions.
o Ovals for Start/Stop
o Rectangles for processes
o Diamonds for decisions (Yes/No)
START END
Processes (Rectangle):
Represents actions or instructions to be performed.
Decision (Diamond):
Represents a decision point where the algorithm branches based on a Yes/No or True/False
condition.
Example:
YES
IS AGE >18
PROCESS 1
NO
PROCESS 2
Input/Output (Parallelogram):
Represents input from the user or output to the user.
Example
Arrows:
Indicate the direction of flow from one step to the next.
Subroutine
Represents a subroutine call that will relate to a separate, non-linked flowchart.
CALL Reorder
SUBROUTINE
START
IF [number] MOD
2=0
TRUE FALSE
END
Example: Reordering stock when low
Problem: Create a flowchart that shows part of an algorithm for a T-shirt system that deals
with re-ordering T-shirts when stocks run low.
Steps:
1. Start
2. Input an item code.
3. Read StockLevel, ReorderLevel
4. Check if StockLevel is less than ReorderLevel
o If Yes, open Reorder subroutine
o If No, No need to order
5. Output the result
6. End
START
NO
END
Why Use Flowcharts?
• They make algorithms easier to understand.
• They are great for visualizing processes.
• They help debug logic before writing actual code.
Pseudo-code:
Pseudocode is a way of writing out the steps of a program in plain and simple words. It is not an
actual programming language, but it helps you plan and organize your code before writing it in a
real programming language like Python or Java.
Think of pseudocode as writing instructions for a computer in a way that looks a bit like English.
You don’t have to worry about grammar, spelling, or even proper computer code rules. The goal
is to make sure anyone reading it can understand the steps your program will follow.
Keyword Meaning
• Comparison operators:
o = (Equals): Checks if two values are the same.
Example: age = 18 (Checks if age is 18.)
o > (Greater than): Checks if one value is bigger than another.
Example: score > 50 (Checks if score is more than 50.)
o < (Less than): Checks if one value is smaller than another.
Example: price < 100 (Checks if price is less than 100.)
• Logical operators:
o AND: Both conditions must be true.
Example: age > 18 AND age < 60 (True if age is between 18 and 60.)
o OR: At least one condition must be true.
Example: age < 18 OR age > 60 (True if age is less than 18 or more than 60.)
1. Sequential Statements
• These are steps the program follows one after the other, in order.
• Think of it as a list of instructions. The program does the first step, then the second, then
the third, and so on.
Example:
INPUT name
OUTPUT "Hello, " + name
This reads the user's name and then prints a greeting.
2. Conditional Statements
• These let the program make decisions.
• The program checks if something is true or false. Based on the answer, it does one thing
or another.
IF...ELSE Statement:
The program does something if a condition is true. If it’s false, it does something else.
Example:
IF age >= 18 THEN
OUTPUT "You are an adult."
ELSE
OUTPUT "You are not an adult."
END IF
This checks grades and gives different outputs depending on the value.
Nested Conditions:
You can put one IF statement inside another.
Example:
IF age >= 18 THEN
IF hasID = TRUE THEN
OUTPUT "You can vote."
ELSE
OUTPUT "You need an ID to vote."
END IF
ELSE
OUTPUT "You are too young to vote."
END IF
Loops
• Loops let the program repeat actions.
• You can repeat actions a set number of times or until something happens.
FOR Loop:
Use this when you know how many times you want to repeat something.
Example:
FOR i = 1 TO 5
OUTPUT i
NEXT i
#This prints the numbers 1 to 5.
WHILE Loop:
Use this when you want to repeat something as long as a condition is true.
Example:
WHILE counter < 10
OUTPUT counter
counter = counter + 1
END WHILE
#This keeps printing the counter value and adding 1 until it reaches 10.
REPEAT...UNTIL Loop:
Similar to WHILE, but it always runs the code at least once, then checks the condition.
Example:
REPEAT
OUTPUT "Enter a number greater than 10:"
INPUT number
UNTIL number > 10
#This keeps asking for a number until the user enters one greater than 10.
Summary of Control Structures
Step-by-Step Explanation:
1. i = 0: The loop starts at the first item (index 0).
2. TO LENGTH(myList) - 1: The loop continues until it reaches the last item.
o LENGTH(myList) is the number of items in the list (here, 4).
o Subtract 1 because the index starts from 0.
3. myList[i]: This gets the item at position i.
o When i = 0, it shows the first item (5).
o When i = 1, it shows the second item (10).
o And so on, until the loop ends.
4. OUTPUT myList[i]: This displays the item.
5. END FOR: The loop finishes after all items are shown.
Summary of Key Points
• Arrays and lists are like boxes that hold many items in order.
• Use an index (starting from 0) to access items.
• Use APPEND to add and REMOVE to delete items.
• Loops are used to go through all the items in a list.
Subroutines (Functions and Procedures)
Subroutines are small parts of a program that do a specific job. There are two main types:
functions and procedures.
• A function does a task and gives back (returns) a value.
• A procedure does a task but does not return a value.
Subroutines are useful because they make programs easier to write, read, and fix. Instead of
repeating the same code in many places, you can just call the subroutine when you need it.
Returning Values
• Only functions return values.
• To return a value, use the RETURN keyword.
• You can save the returned value in a variable or use it directly.
Example:
FUNCTION SquareNumber(x)
result = x * x
RETURN result
END FUNCTION
square = SquareNumber(4)
OUTPUT square // This will print 16
Explanation:
• The user types three numbers: num1, num2, and num3.
• The program checks which number is bigger using IF and ELSE IF.
• It shows the largest number with OUTPUT.
Example 3: Check if a Number is Even or Odd
This program will take a number and tell if it is even or odd.
Pseudocode:
START
INPUT number
IF number MOD 2 = 0 THEN
OUTPUT "The number is even"
ELSE
OUTPUT "The number is odd"
END IF
END
Explanation:
• The user types a number.
• MOD checks if the number can be divided by 2 with no remainder.
• If yes, the program says it’s even. If no, it says it’s odd.
Example 4: Simple Login System
This program checks if the username and password are correct.
Pseudocode:
START
username ← "student"
password ← "1234"
INPUT inputUsername
INPUT inputPassword
IF inputUsername = username AND inputPassword = password THEN
OUTPUT "Login successful"
ELSE
OUTPUT "Login failed"
END IF
END
Explanation:
• The program stores the correct username and password.
• The user, types their username and password.
• The program checks if they match.
• It shows "Login successful" if they match, otherwise "Login failed."
Common Mistakes to Avoid in Pseudocode
When writing pseudocode, students often make mistakes that can confuse the reader or lead to
incorrect answers.
2. Missing Steps
Problem: Forgetting to include important parts of the algorithm.
Example: Writing the steps to calculate the average but forgetting to add up the numbers
first.
Solution: Check your logic step by step. Think, "What must happen first, second, and so
on?"
7. Misusing Loops
Problem: Choosing the wrong type of loop or forgetting the stopping condition.
Example: A WHILE loop without a condition will run forever.
Solution: Think about how many times the loop should run and write the condition
clearly.
Solution:
START
OUTPUT "Enter the first number:"
INPUT number1
OUTPUT "Enter the second number:"
INPUT number2
total ← number1 + number2
OUTPUT "The total is:", total
END
Intermediate Exercise: Find the Largest Number in a List
Write pseudocode to:
1. Create a list of five numbers.
2. Find the largest number in the list.
3. Show the largest number.
Solution:
START
numbers ← [10, 25, 5, 8, 15]
largest ← numbers[0]
FOR each number IN numbers
IF number > largest THEN
largest ← number
END IF
END FOR
OUTPUT "The largest number is:", largest
END
Advanced Exercise: ATM Withdrawal System
Write pseudocode to:
1. Ask the user to enter their PIN.
2. If the PIN is correct, ask them how much money they want to withdraw.
3. Check if they have enough money in their account.
4. If they do, show a success message. If not, show an error message.
Solution:
START
PIN ← 1234
balance ← 500
OUTPUT "Enter your PIN:"
INPUT userPIN
IF userPIN = PIN THEN
OUTPUT "Enter the amount to withdraw:"
INPUT amount
IF amount <= balance THEN
balance ← balance - amount
OUTPUT "Withdrawal successful. Your new balance is:", balance
ELSE
OUTPUT "Error: Not enough funds."
ENDIF
ELSE
OUTPUT "Error: Incorrect PIN."
ENDIF
Summary and Quick Reference
This section is a quick guide to the most important pseudocode rules and structures. Use it to
revise or check your work.
Example:
IF score > 50 THEN
OUTPUT "You passed"
ELSE
OUTPUT "You failed"
END IF
• Loops:
• To repeat steps:
o FOR loop:
FOR counter FROM start TO end DO
do something
END FOR
Example
FOR i FROM 1 TO 10 DO
OUTPUT i
END FOR
o WHILE loop:
WHILE condition DO
do something
END WHILE
Example:
WHILE score < 100 DO
SET score TO score + 10
ENDWHILE
o REPEAT...UNTIL loop:
REPEAT
do something
UNTIL condition
Example:
REPEAT
INPUT score
UNTIL score >= 0
• Arrays:
• To store multiple items:
SET arrayName TO [item1, item2, item3]
Example:
SET numbers TO [2, 4, 6, 8]
• To access an item:
arrayName[position]
Example:
OUTPUT numbers[2] //displays 4
▪ Functions/Procedures:
• To write reusable code:
PROCEDURE procedureName(parameters)
do something
END PROCEDURE
Example:
PROCEDURE DisplayMessage(name)
OUTPUT "Hello, ", name
END PROCEDURE
Summary of Pseudocode
Trace Table:
• A trace table helps you test your pseudocode by tracking how variables change.
• Draw a table with columns for variables, inputs, and outputs.
• Follow your pseudocode line by line, filling in the table with values as they change.
• Use the trace table to check if the output is correct and to find errors.
• Practice using trace tables to improve your understanding of pseudocode.
6. Efficiency of Algorithms
Different algorithms can solve the same problem, but some are faster or take fewer steps. For example:
• Finding the greatest common divisor of two numbers using two different methods:
o One method subtracts numbers repeatedly (efficient).
o Another method divides numbers by every possible value (inefficient).
When we write an algorithm, we want it to solve a problem as quickly and efficiently as possible.
Efficiency means how well the algorithm uses time and resources like memory. There are two main
things we look at when thinking about efficiency:
1. Time Efficiency
o This is about how fast the algorithm works.
o Some algorithms take more steps to finish as the size of the input (data) gets bigger. For
example, if you are sorting a list of 10 numbers, it will take less time than sorting a list of
1,000 numbers.
o We want to write algorithms that can handle large amounts of data without slowing down
too much.
2. Space Efficiency
o This is about how much memory the algorithm uses.
o If an algorithm uses too much memory, it might not work well on devices with limited
space.
o A good algorithm uses as little memory as possible while still solving the problem.
Why Does Efficiency Matter?
• Imagine you are using an app on your phone, and it takes too long to load or crashes because it
needs too much memory. That app might be using an inefficient algorithm.
• Efficient algorithms make programs faster, smoother, and more reliable.
How to Measure Efficiency
• One way to compare algorithms is to count how many steps they need to finish a task.
• We also look at how the number of steps changes as the input grows larger.
o Example: If you have a list with 10 names, does the algorithm take twice as long with 20
names? What about 100 names?
• The fewer steps it takes, the more efficient the algorithm is.
Choosing the Right Algorithm
• Not all problems need the fastest or most efficient algorithm.
• Sometimes, a simple algorithm is enough, especially if the input size is small.
• For large problems, it’s worth spending time to design or choose a more efficient algorithm.
Summary of Efficiency of Algorithms
• Efficiency is about how fast and how much memory an algorithm uses.
• Time efficiency measures how quickly an algorithm finishes its task.
• Space efficiency measures how much memory an algorithm needs.
• Efficient algorithms work better with large amounts of data.
• Choose the right algorithm based on the size and needs of the problem.
7. Sorting Algorithms
Sorting is a way of arranging data in a specific order, like from smallest to largest or largest to
smallest. It helps us organize data, so it is easier to use.
Bubble sort and Merge sort are two common ways to sort data.
Bubble Sort
What is Bubble Sort?
Bubble Sort is a simple method to sort data. It works by comparing two items at a time. If the
first one is bigger, they swap places. This is repeated until everything is sorted.
START Merge
INPUT two sorted lists
OUTPUT combined sorted list
WHILE both lists are not empty DO
IF first item of left ≤ first item of right THEN
ADD first item of left to result
REMOVE first item from left
ELSE
ADD first item of right to result
REMOVE first item from right
END IF
END WHILE
ADD remaining items from non-empty list to result
RETURN result
END Merge
• Bubble Sort:
o Compares two items at a time.
o Swaps them if needed.
o Repeats until the list is sorted.
o Simple to understand but slow for large lists.
• Merge Sort:
o Divides the list into smaller parts.
o Sorts and merges them back together.
o Faster than Bubble Sort for large lists but more complex to write.
8. Searching Algorithms
When you need to find something in a list or an array, you use a searching algorithm. The most common
ones in GCSE are Linear Search and Binary Search.
Linear Search
A Linear Search looks through a list one item at a time until it finds what you are looking for. It is
simple and works for any list, even if the items are not in order.
Example Problem: Find the number 5 in the list [3, 7, 5, 9].
Pseudocode:
START
INPUT the list
INPUT the number to search for
FOR each item in the list:
IF the item equals the number:
OUTPUT "Number found"
STOP
ELSE
OUTPUT "Number not found"
END IF
END
How it works:
1. Start at the first item in the list.
2. Check each item one by one.
3. Stop if you find the item. If you check the whole list and don’t find it, say it’s not there.
Binary Search
A Binary Search is faster but only works if the list is in order. It keeps dividing the list into halves
to find the item.
Example Problem: Find the number 6 in the list [2, 4, 6, 8, 10].
Pseudocode:
START
INPUT the sorted list
INPUT the number to search for
SET start = 0
SET end = length of list - 1
How it works:
1. Start by looking at the middle item.
2. If the middle item is what you’re looking for, stop.
3. If it’s smaller than your number, only check the right half.
4. If it’s bigger, only check the left half.
5. Repeat until you find the number, or the list is empty.
Summary of Searching Algorithms
• Linear Search:
o Looks at each item one by one.
o Works on any list (ordered or unordered).
o Slower for big lists.
• Binary Search:
o Only works on sorted lists.
o Divides the list into halves to find the item.
o Much faster for big lists.