0% found this document useful (0 votes)
30 views

1 - Fundamentals of Algorithms

AQA GCSE Computer Science

Uploaded by

Liane Regnard
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

1 - Fundamentals of Algorithms

AQA GCSE Computer Science

Uploaded by

Liane Regnard
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

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.

2. Decomposition and Abstraction


To solve problems effectively, we use two techniques:
1. Decomposition: Breaking down a big problem into smaller, manageable parts.
Example: Building a T-shirt sales system might involve:
o A login system
o A search function
o A checkout process
2. Abstraction: Removing unnecessary details to focus on the important ones.
Example: On a London Underground map, the map shows only the station connections, not the
exact distances or street details.

3. Inputs, Processes, and Outputs


Algorithms take inputs, process them, and produce outputs. This is called the Input-Process-Output
(IPO) model.
Example: T-shirt Search System
• Inputs: Size, colour, style of T-shirt.
• Process: Search for matching T-shirts in the database.
• Output: List of T-shirts that match the user's criteria.
4. Representing Algorithms
You can represent algorithms using:

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)

Key Components of a Flowchart


Terminal (Start/End) (Oval):
o This shape is used to indicate the start or end of the process.
o Example

START END

Processes (Rectangle):
Represents actions or instructions to be performed.

CALCULATE TOTAL = PRICE * QUANTITY

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

INPUT "Enter your name" OUTPUT "Hello, [name]"

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

How to Read a Flowchart


Follow the arrows from the "Start" shape and move step-by-step through each shape, making
decisions or performing actions as directed. When you reach "Stop," the process ends.

Example Flowchart: Odd or Even Checker


Problem: Write a flowchart to check if a number is odd or even.
Steps:
1. Start.
2. Input a number.
3. Check if the number is divisible by 2.
o If Yes, the number is even.
o If No, the number is odd.
4. Output the result.
5. Stop.
Flowchart Representation:

START

INPUT "Please enter a


number"

IF [number] MOD
2=0

TRUE FALSE

OUTPUT “Your OUTPUT “Your


number is even” number is odd”

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

INPUT "Please enter


ItemCode”

READ StockLevel, ReorderLevel

IF StockLevel ≤ YES CALL Reorder


ReorderLevel SUBROUTINE

NO

OUTPUT “No need OUTPUT “Stock


for new order” has been ordered”

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.

Why Is Pseudocode Important?


• Easy to Understand: Pseudocode is simple. Even if someone doesn’t know how to code,
they can understand the logic.
• Good for Planning: Before writing code, you can use pseudocode to organize your ideas.
This makes it easier to spot mistakes or missing steps.
• Useful for Exams: In GCSE exams, you will need to read and write pseudocode to show that
you understand how a program works.

What Does Pseudocode Look Like?


Pseudocode uses clear and logical words like:
• INPUT for getting data from the user.
• OUTPUT for showing results to the user.
• IF and ELSE for decisions.
• FOR and WHILE for repeating steps (loops).
Example:
If you wanted to tell a computer to add two numbers and show the answer, you might write:
INPUT number1
INPUT number2
total = number1 + number2
OUTPUT total
What’s the Difference Between Pseudocode and Real Code?
Pseudocode:
• Doesn’t follow strict rules.
• Is written in a mix of plain English and programming concepts.
• Focuses on the idea of what the program will do.
Real Code:
• Must follow the exact rules of a programming language.
• Can be run on a computer.
• Is more detailed and complex.

Key Words and Their Meanings


Here are some common pseudo-code terms and what they mean:

Keyword Meaning

INPUT Accepts data from the user (e.g., "Enter a number").

OUTPUT Displays data to the user (e.g., "The result is 10").

IF ... THEN Represents a decision point. Used for conditions.

ELSE Describes the alternative if the IF condition is not true.

FOR ... TO A loop that repeats a specific number of times.

WHILE ... DO A loop that repeats as long as a condition is true.

END IF Marks the end of an IF statement.

← Assigns a value to a variable (e.g., x ← 5 means "set x to 5").


Structure of Pseudocode
Pseudocode is a way of writing down the steps of a program in plain English. It does not follow
strict rules like real programming languages, but it still needs to be clear and easy to follow.
When writing pseudocode, imagine you are giving instructions to someone who knows a little
about computers but doesn’t need to know any specific coding language.

1. Start with a Clear Goal


• Begin by writing what the program is supposed to do.
• Example: "This program calculates the total of two numbers."

2. Use Simple Words and Commands


• Write the steps clearly, one at a time.
• Use simple commands like INPUT, OUTPUT, IF, WHILE, or FOR.

3. Indent to Show Blocks of Code


• Indentation makes it clear what happens inside a condition or loop.
• Example:
IF age >= 18 THEN
OUTPUT "You can vote."
ENDIF

4. Use CAPITAL LETTERS for Commands


• GCSE exams usually want you to write keywords like INPUT, OUTPUT, and IF in
uppercase letters so they stand out.

5. Number or List Steps if Necessary


• For some programs, numbering the steps or using bullet points can make your
pseudocode easier to follow.
6. Avoid Long Sentences
• Each step should explain one task.
• Instead of:
“Ask the user for their name, then check if it is in the system, and then print a welcome
message if it is.”
Write:
INPUT name
IF name is in system THEN
OUTPUT "Welcome!"
ENDIF

7. End the Program


• Clearly mark where the program ends.
• Example: END

Example of Well-Structured Pseudocode


This example shows a program to find the sum of two numbers:
START
INPUT number1
INPUT number2
sum = number1 + number2
OUTPUT sum
END

Summary: Structure of Pseudocode

• Start with the program's goal.


• Write steps in simple and clear language.
• Use uppercase for keywords like INPUT, OUTPUT, IF, and FOR.
• Indent to show blocks of code (e.g., inside loops or conditions).
• Keep each step short and focused on one task.
• End the program with END.
Basic Components
In pseudocode, you use simple language to show how a program works.

1. Variables and Data Types


A variable is like a container that holds information.
You can give the container a name and put something inside it, like a number or a word.
• To create a variable, write:
variableName ← value
Example:
age ← 15 //This creates a variable called "age" and sets it to 15
ItemCode ← USERINPUT //This creates a variable called “ItemCode” which
allows the user to input data into
• Variables can hold:
o Numbers (e.g., 10, 3.5).
o Words or text (e.g., "Hello").
o True/False values (e.g., TRUE or FALSE).

2. Input and Output


• Input:
This is how the program gets information from the user.
Example:
name ← INPUT
#The program asks the user to type their name, and it stores it in the variable
name.
• Output:
This is how the program gives information to the user.
Example:
OUTPUT "Welcome!"
#The program shows the text "Welcome!" on the screen.
3. Operators
Operators are symbols or words used to do things like math, compare numbers, or make
decisions.
• Math operators:
o + (Add): sum ← 10 + 5 → Adds 10 and 5 to make 15.
o - (Subtract): difference ← 10 - 5 → Subtracts 5 from 10 to make 5.
o * (Multiply): product ← 10 * 5 → Multiplies 10 by 5 to make 50.
o / (Divide): result ← 10 / 2 → Divides 10 by 2 to make 5.

• 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.)

Summary of Basic Components

• Variables: Containers that hold data. Example: score ← 100.


• Input: Lets the program get data from the user. Example: name ← INPUT.
• Output: Shows information to the user. Example: OUTPUT "Hello!".
• Math operators: +, -, *, / for calculations.
• Comparison operators: =, <, >, to compare values.
• Logical operators: AND, OR for making decisions.
Control Structures
Control structures are the rules that decide the flow of your program.
They tell the computer what to do next based on conditions or repeated actions.
In pseudocode, there are three main types of control structures:

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

If the age is 18 or more, it says, “You are an adult.”


Otherwise, it says, “You are not an adult.”
ELSE IF Statement:
Use this when there are multiple conditions to check.
Example:
IF grade >= 90 THEN
OUTPUT "A"
ELSE
IF grade >= 80 THEN
OUTPUT "B"
ELSE
OUTPUT "C"
END IF
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

• Sequential Statements: Do steps in order.


• Conditional Statements: Make decisions with IF, ELSE, and ELSE IF.
• Loops: Repeat actions using FOR, WHILE, or REPEAT...UNTIL.
These rules help programs decide what to do next and when to stop.
Arrays and Lists
What Are Arrays and Lists?
• Arrays and lists are like boxes that hold many items.
• Each item is stored in order, and we can pick them out using a number called the index.
• Think of it like a row of lockers. Each locker has a number (index), and inside is an item
(value).

How to Create an Array or List


• To make an array or list, you write a name and the items you want to store.
Example:
myList = [2, 4, 6, 8, 10]
Here, myList is the name of the array, and it holds the numbers 2, 4, 6, 8, and 10.

How to Access Items in an Array or List


• To get an item from a list, use its index (the position number).
• Remember, the first item has an index of 0.
Example:
OUTPUT myList[0] // This shows 2 (the first item)
OUTPUT myList[3] // This shows 8 (the fourth item)

How to Change an Item in a List


• You can replace an item by using its index.
Example:
myList[1] = 5 // Changes the second item (4) to 5

How to Add Items to a List


• Use APPEND to add an item to the end of the list.
Example:
APPEND myList, 12 // Adds 12 to the list
How to Remove Items from a List
• Use REMOVE to take an item out of the list.
Example:
REMOVE myList[2] // Removes the third item (6)

How to Loop Through a List


• A loop helps you check or use every item in a list one by one.
Example:
FOR i = 0 TO LENGTH(myList) - 1
OUTPUT myList[i]
END FOR
#This prints all the items in the list underneath each other.

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.

How to Write a Subroutine


1. Declare the Subroutine
• Use a name that shows what the subroutine does.
• List any input values (parameters) the subroutine needs to work.
Example for a function:
FUNCTION AddNumbers(a, b)
total = a + b
RETURN total
END FUNCTION

Example for a procedure:


PROCEDURE SayHello(name)
OUTPUT "Hello, " + name
END PROCEDURE

2. Call the Subroutine


• To use a subroutine, just call it by its name and provide any needed input values.
Example of calling AddNumbers:
result = AddNumbers(5, 10)
OUTPUT result // This will print 15

Example of calling SayHello:


SayHello("Alex") // This will print: Hello, Alex
Using Parameters
• Parameters are the values you give to a subroutine when you call it.
• In AddNumbers(a, b), a and b are the parameters.
• You can use as many parameters as you need.

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

Why Use Subroutines?


• They save time because you don’t have to write the same code multiple times.
• They make your program shorter and easier to understand.
• They help you find and fix mistakes faster.
Summary of Subroutines

• Subroutines are small sections of a program that do one job.


• There are two types:
o Functions return a value.
o Procedures do not return a value.
• Use parameters to pass data into a subroutine.
• Use RETURN in functions to send back a value.
• Subroutines make programs easier to write, read, and debug.
Practical Examples
These examples will help you see how to solve problems step by step. Don’t worry if the
problems seem hard at first. Follow the steps, and it will become clearer.

Example 1: Add Two Numbers


This program will take two numbers from the user, add them together, and show the result.
Pseudocode:
START
INPUT number1
INPUT number2
result ← number1 + number2
OUTPUT "The sum is", result
END
Explanation:
• INPUT means the user types in two numbers.
• The numbers are stored in number1 and number2.
• result adds number1 and number2 together.
• OUTPUT shows the sum to the user.
Example 2: Find the Largest Number
This program will take three numbers from the user and find the largest.
Pseudocode:
START
INPUT num1
INPUT num2
INPUT num3
IF num1 > num2 AND num1 > num3 THEN
OUTPUT "The largest number is", num1
ELSE
IF num2 > num1 AND num2 > num3 THEN
OUTPUT "The largest number is", num2
ELSE
OUTPUT "The largest number is", num3
END IF
END IF
END

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.

1. Writing Ambiguous Logic


Problem: Some students write steps that are unclear or hard to follow.
Example: "Check if the input is okay" does not explain what "okay" means.
Solution: Be specific. Write something like:
IF input > 0 THEN
Or
IF input is NOT empty THEN.

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?"

3. Using Programming Language Syntax


Problem: Mixing up pseudocode with actual code (e.g., writing int x = 5; instead of x = 5).
Solution: Remember that pseudocode is plain English with simple structures. It does not
need detailed syntax.

4. Overcomplicating the Solution


Problem: Adding unnecessary steps or overthinking simple problems.
Example: Using loops when a simple condition will do.
Solution: Keep it simple. Use the easiest way to solve the problem.
5. Ignoring Input and Output
Problem: Forgetting to include INPUT or OUTPUT steps.
Example: Writing a sorting algorithm but not stating where the numbers come from or
how the sorted list is shown.
Solution: Always mention what the user gives (INPUT) and what the program shows
(OUTPUT).

6. Not Using Proper Indentation


Problem: Writing everything in one line or not showing which steps belong to loops or
conditions.
Example:
IF x > 10
PRINT "High"
END IF
is harder to read than:
IF x > 10 THEN
PRINT "High"
END IF
Solution: Use indentation to show structure.

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.

8. Not Testing the Logic


Problem: Writing pseudocode without checking if it works.
Solution: Test your pseudocode by imagining you are the computer. Follow the steps and
see if they make sense.
Summary of Common Mistakes

• Be clear and specific; avoid vague instructions.


• Include all the necessary steps.
• Do not mix programming code with pseudocode.
• Keep your solution simple and logical.
• Always include INPUT and OUTPUT steps.
• Use indentation to make your pseudocode easy to read.
• Choose the right loop and write its stopping condition.
• Test your pseudocode to make sure it works.
Exam Preparation Tips
When you prepare for pseudocode questions in your exam, follow these simple steps to do well:
1. Understand the Question
• Read the question carefully.
• Look for key words like "input," "output," "loop," or "condition."
• Make sure you know what the question is asking you to solve.

2. Plan Before You Write


• Think about the steps needed to solve the problem.
• Write the steps in plain English first if it helps.
• Then, turn these steps into pseudocode.

3. Write Clearly and Neatly


• Use simple, clear instructions.
• Follow a proper structure (e.g., IF...ELSE, loops).
• Do not add unnecessary details.

4. Check Your Logic


• Think: Does your pseudocode solve the problem?
• Imagine you are a computer following the steps.
• Check for missing steps or errors.

5. Learn Common Patterns


• Practice writing pseudocode for common problems, like calculating a total or finding the
largest number in a list.
• These types of problems often appear in exams.

6. Debug Given Pseudocode


• Sometimes, you will be asked to fix or explain pseudocode.
• Read the pseudocode slowly.
• Check for missing steps, incorrect conditions, or wrong loops.
7. Manage Your Time
• Spend a few minutes planning your answer.
• Do not spend too long on one question. Move on if you are stuck and come back later.

8. Practice with Past Papers


• Practice with real exam questions.
• This will help you get used to the style of the questions.
• Check your answers to see what you got right or wrong.

Summary of Exam Tips

• Understand the question: Read carefully and know what it wants.


• Plan your answer: Think before you write pseudocode.
• Be clear and neat: Write step-by-step in simple pseudocode.
• Check your logic: Does it work? Are any steps missing?
• Practice patterns: Learn common problems like loops or conditions.
• Fix pseudocode: If asked, look for mistakes and correct them.
• Use your time wisely: Plan your answer, don’t get stuck too long.
• Practice exams: Use past questions to prepare and learn.
Practice Exercises
Each exercise starts easy and becomes a little harder as you go.

Beginner Exercise: Add Two Numbers


Write pseudocode to:
1. Ask the user to enter two numbers.
2. Add the two numbers together.
3. Show the total.

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.

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.
Beginner Exercise: Add Two Numbers
Write pseudocode to:
1. Ask the user to enter two numbers.
2. Add the two numbers together.
3. Show the total.

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.

Key Rules for Pseudocode


1. Write in simple and clear steps.
2. Use capital letters for keywords like INPUT, OUTPUT, IF, and WHILE.
3. Always make sure your logic is easy to follow.
4. Use indentation for steps inside loops or conditions.

Common Pseudocode Commands


• Variables:
o To store information, write:
SET variableName TO value
Example: SET score TO 0

• Input and Output:


o To take input from the user:
INPUT variableName
Example: INPUT age
o To display output:
OUTPUT message or variable
Example: OUTPUT "Your score is", score
• Conditional Statements:
o To make decisions:
IF condition THEN
do something
ELSE
do something else
END IF

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

• Variables: Use SET to give a variable a value.


• Input: Use INPUT to get information from the user.
• Output: Use OUTPUT to show a result or message.
• Conditions: Use IF...ELSE to make decisions.
• Loops: Use FOR, WHILE, or REPEAT...UNTIL for repeating tasks.
• Arrays: Store and access multiple values with SET arrayName.
• Functions: Reuse code with PROCEDURE blocks.
• Indentation: Show which steps belong inside loops or conditions.
• Capitalization: Write keywords like IF, FOR, and INPUT in capital letters.
5. Using a Trace Table
A trace table is a way to check if your pseudocode works correctly. It helps you follow the steps of your
program and see how the values of variables change as the program runs. You can use a trace table to
check for mistakes and understand how the program works.

How a Trace Table Works


1. Draw a Table:
Create a table with columns for each variable in your program. Also, add columns for any
inputs and outputs.
2. List the Steps:
Write down each step or line of your pseudocode in order.
3. Fill in the Values:
As you follow each step, write down the value of each variable. If a value changes, write the
new value in the next row.
4. Check the Outputs:
Record any outputs produced by your program to ensure they are correct.
Example
Here’s an example of using a trace table:
Pseudocode:
INPUT num1
INPUT num2
sum ← num1 + num2
OUTPUT sum

Trace Table:

Step Num1 Num2 Sum Output


1 5 - - -
2 5 10 - -
3 5 10 15 -
4 5 10 15 15

• Step 1: num1 is set to 5.


• Step 2: num2 is set to 10.
• Step 3: sum is calculated as 5 + 10 = 15.
• Step 4: The program outputs sum, which is 15.
The trace table shows that the program works correctly because the output matches the
expected value.
Why Use Trace Tables?
• They help you find mistakes in your pseudocode.
• They make it easier to see how a program works step by step.
• They are a great way to check your answers in exams.

Summary of Truth Tables

• 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.

How Bubble Sort Works


1. Start at the beginning of the list.
2. Compare the first and second items.
3. If the first is bigger than the second, swap them.
4. Move to the next pair and repeat.
5. Continue until the end of the list.
6. Repeat the whole process until no swaps are needed.

Pseudocode for Bubble Sort


START BubbleSort
INPUT “Please enter list of numbers”
REPEAT
Example for Bubble Sort
swapped ← False
List: [6, 4, 7, 2]
FOR i ← 0 TO length of list - 2 DO
1. Compare 6 and 4: Swap →
IF list[i] > list[i + 1] THEN [4, 6, 7, 2]
SWAP list[i] WITH list[i + 1] 2. Compare 6 and 7: No swap.
swapped ← True 3. Compare 7 and 2: Swap →
END IF [4, 6, 2, 7]

END FOR 4. Repeat until final sorted list:


[2, 4, 6, 7]
UNTIL swapped = False
OUTPUT sorted list
END BubbleSort
Merge Sort
What is Merge Sort?
Merge Sort is a more efficient sorting method. It splits the list into smaller parts, sorts each part,
and then combines (merges) them back together in order.

How Merge Sort Works


1. Divide the list into two halves.
2. Keep dividing each half until each part has one item.
3. Merge the small parts together in the correct order.
4. Continue merging until the entire list is sorted.

Pseudocode for Merge Sort


START MergeSort
IF size of list ≤ 1 THEN Example for Merge Sort
List: [8, 3, 5, 1]
RETURN list
ELSE 1. Split: [8, 3] and [5, 1]
2. Split further: [8], [3], [5], [1]
middle ← length of list ÷ 2 3. Merge [8] and [3] → [3, 8]
4. Merge [5] and [1] → [1, 5]
left ← first half of list
5. Merge [3, 8] and [1, 5] → [1, 3, 5, 8]
right ← second half of list
sortedLeft ← MergeSort(left)
sortedRight ← MergeSort(right)
RETURN Merge(sortedLeft, sortedRight)
END IF
END MergeSort

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

Summary of Sorting Algorithms

• 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

WHILE start <= end:


SET middle = (start + end) DIV 2
IF list[middle] equals the number:
OUTPUT "Number found"
STOP
ELSE IF list[middle] < the number:
SET start = middle + 1
ELSE:
SET end = middle - 1

OUTPUT "Number not found"


END

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy