Created by Turbolearn AI
Program Development Life Cycle
The program development life cycle includes several key stages to ensure a problem
is effectively solved through software.
Analysis
The analysis stage of the program development life cycle is to precisely
understand the problem the program is intended to solve.
The Role of Abstraction
Abstraction is removing unimportant details from a problem to focus on important
elements such as:
Core functionality
Requirements
Page 1
Created by Turbolearn AI
Consider the London Underground map. It's a great example of abstraction; travelers
don't need to know the geographical layout of the routes, only that getting on at stop
A will eventually transport them to stop B.
Core Functionality
Using abstraction helps identify the fundamental components of what the program
will solve. Before tackling a problem, it needs to be clearly understood by everyone
involved. The overall goal of the solution needs to be agreed upon, as well as any
constraints such as limited resources or requiring a platform-specific solution.
Requirements
To create a solution, a requirements document is created to define the problem and
break it down into clear, manageable, and understandable parts by using abstraction
and decomposition. A requirements document labels each requirement, gives it a
description, as well as success criteria which state how we know when the
requirement has been achieved.
Design
The design stage of the program development life cycle involves using
techniques to come up with a blueprint for a solution.
Ways the design of a solution to a problem can be presented include:
Structure diagrams
Flowcharts
Pseudocode
Coding
The coding stage of the program development life cycle is when
developers begin programming modules in a suitable programming
language that work together to provide an overall solution to the
problem.
Page 2
Created by Turbolearn AI
As each developer programs, they perform iterative testing. Iterative testing is
where each module is tested and debugged thoroughly to make sure it interacts
correctly with other modules and accepts data without crashing or causing any
errors. Developers may need to retest modules as new modules are created and
changed to make sure they continue to interact correctly and do not cause errors.
Testing
The testing stage of the program development life cycle is when the
overall program or set of programs is run many times using varying sets
of test data.
This ensures the program or programs work as intended as outlined in the initial
requirements specification and design and rejects any invalid data that is input.
Examples of test data include alphanumeric sequences to test password validation
routines.
Computer Sub-Systems
What is a Sub-System?
A sub-system is a smaller part of a computer system that works together
with other sub-systems to create a fully functional computer system.
A car is a great example of using sub-systems:
Engine
Breaks
Wheels
The car will only function if its sub-systems all work together. Sub-systems can be
further broken down into even smaller sub-systems, such as:
Engine - spark plugs, sensors, pistons
In computers, there are five main sub-systems:
Page 3
Created by Turbolearn AI
Computer Sub-system Description
Central Processing Unit
Executes instructions
(CPU)
Memory Stores data & instructions temporarily for the CPU (RAM)
Storage Stores data and software permanently (HDD, SSD)
Input devices Allows a user to enter information (keyboard, mouse)
Displays information or creates a physical output
Output devices
(monitor, printer)
Computer sub-systems can be further broken down into smaller sub-systems, such
as:
CPU - control unit, registers & arithmetic logic unit (ALU)
Advantages of Sub-Systems
Can help troubleshoot problems in a computer system.
The ability to isolate a sub-system makes it easier to identify and fix issues, as
each sub-system can be examined separately.
Developing software relies on the use of different sub-systems to ensure they
operate efficiently.
Gives developers and designers a clear picture of how sub-systems help build
complex systems.
Problem Decomposition
What is Decomposition?
Decomposition is the process of breaking down a large problem into a set
of smaller problems.
Benefits of decomposition are:
Smaller problems are easier to solve.
Each smaller problem can be solved independently of the others.
Smaller problems can be tested independently.
Smaller problems can be combined to produce a solution to the full problem.
Page 4
Created by Turbolearn AI
Modern computer games are a good example of using decomposition to break down
the complexity of the problem into more manageable 'chunks'. Creating an entire
game at once would be challenging and inefficient, so it could be decomposed into:
Levels - Levels can be designed/created/tested independently of other levels
Characters - The mechanics of characters in the game can be designed and
created by a separate team
Landscape - The art team can work on the visual aspects of the game without
needing to understand how the game is programmed
Once all of the smaller problems are completed, joined together a complex game has
been created.
Inputs, Processes, Outputs and Storage
Decomposing a problem requires developers to think about four component parts:
Inputs: data entered into the system
Processes: subroutines and algorithms that turn inputs and stored data into
outputs
Outputs: data that is produced by the system, such as information on a screen
or printed information
Storage: data that is stored on a physical device, such as on a hard drive or in
memory whilst the program is running
Example - Area of a Rectangle Program
Inputs Width of the rectangle Height of the rectangle
Processes Width x height
Outputs Calculated area of the rectangle
Storage Memory: width, height and area stored temporarily
Designing Algorithms
What is an Algorithm?
Page 5
Created by Turbolearn AI
An algorithm is a precise set of rules or instructions to solve a specific
problem or task.
There are three main ways to design an algorithm:
Structure diagrams
Flowcharts
Pseudocode
Structure Diagrams
Structure diagrams show hierarchical top-down design in a visual form.
Each problem is divided into sub-problems and each sub-problem divided
into further sub-problems. At each level the problem is broken down into
more detailed tasks that can be implemented using a single subroutine.
The image shows a system broken down into three sub-systems, with one of those
sub-systems being further broken down.
As an example, a structure diagram for a mobile application could break down the
application into modules like voice calls, text messages, and contact data store.
Page 6
Created by Turbolearn AI
The image shows a high-level flowchart for a mobile phone and its functions.
Flowcharts
Flowcharts are a visual tool that uses shapes to represent different
functions to describe an algorithm.
Flowcharts show the data that is input and output, the processes that take
place, and any decisions or repetition. Lines are used to show the flow of
control.
The image above is a great cheat sheet describing the purpose of each shape used
within flowcharts.
Example Flowchart
Page 7
Created by Turbolearn AI
The flowchart begins with a start, takes in user's age, and outputs "Welcome to the
site" if the age is greater than or equal to 18.
Imagine a casino would like the algorithm refined so that the user also enters their
first name, and this is used to greet the user when they access the site.
Page 8
Created by Turbolearn AI
The image shows a flowchart that now includes the user's name to output a
personalized welcome.
Pseudocode
Pseudocode is a text-based tool that uses short English
words/statements to describe an algorithm. Pseudocode is more
structured than writing sentences in English but is very flexible.
Page 9
Created by Turbolearn AI
Example
A casino would like a program that asks users to enter an age, if they are 18 or over
they can enter the site, if not then they are given a suitable message.
INPUT Age
IF Age >= 18 THEN
OUTPUT "Welcome to the site"
ELSE
OUTPUT "Sorry, this site is for users 18 and over"
ENDIF
If the algorithm is refined so that the user also enters their first name and this is used
to greet the user when they access the site:
INPUT FName
INPUT Age
IF Age >= 18 THEN
OUTPUT "Welcome to the site", FName
ELSE
OUTPUT "Sorry, this site is for users 18 and over"
ENDIF
Explaining Algorithms
How to Explain an Algorithm
A well-designed algorithm should be able to be interpreted by a new user, and they
should be able to explain what it does. Algorithms can be written using flowcharts,
pseudocode, or high-level programming language code such as Python.
The purpose of an algorithm is to solve a problem. If a user does not know the goal
of the algorithm, then following the algorithm instructions should make its purpose
clear.
If the algorithm is complex, then additional ways to understand the problem could
be:
Look for comments in the code.
Consider the context of where the algorithm is being used.
Test the algorithm with different inputs.
Page 10
Created by Turbolearn AI
Look at the following algorithm, can you explain what it does?
Count ← 1
Number ← 0
Total ← 0
REPEAT
INPUT Number
Total ← Total + Number
Count ← Count + 1
UNTIL Count > 10
OUTPUT Total
The purpose of the algorithm is to add ten user-entered numbers together and
output the total.
The processes are:
Initializing three variables (Count, Number, Total)
Inputting a user number
Adding to two variables (Total, Count)
Repeating nine more times
Outputting the final Total value
Worked Example
The pseudocode algorithm shown has been written by a teacher to enter marks for
the students in her class and then to apply some simple processing.
Page 11
Created by Turbolearn AI
Count ← 0
REPEAT
INPUT Score[Count]
IF Score[Count] >= 70 THEN
Grade[Count] ← "A"
ELSE IF Score[Count] >= 60 THEN
Grade[Count] ← "B"
ELSE IF Score[Count] >= 50 THEN
Grade[Count] ← "C"
ELSE IF Score[Count] >= 40 THEN
Grade[Count] ← "D"
ELSE IF Score[Count] >= 30 THEN
Grade[Count] ← "E"
ELSE
Grade[Count] ← "F"
ENDIF
ENDIF
ENDIF
ENDIF
ENDIF
Count ← Count + 1
UNTIL Count = 30
Describe what happens in this algorithm.
Answer
Any 3 of:
Inputted marks are stored in the array Score[] [1]
Marks are then checked against a range of boundaries [1]
A matching grade is assigned to each mark that has been input [1]
The grade is then stored in the array Grade[] [1]
At the same index as the inputted mark [1]
The algorithm finishes after 30 marks have been input [1]
Standard Methods of a Solution
Linear Search
Searching algorithms are precise step-by-step instructions that a
computer can follow to efficiently locate specific data in massive datasets.
Page 12
Created by Turbolearn AI
A linear search starts with the first value in a dataset and checks every
value one at a time until all values have been checked. A linear search can
be performed even if the values are not in order.
How to Perform a Linear Search
Step Instruction
1 Check the first value
2 IF it is the value you are looking for STOP!
3 ELSE move to the next value and check
REPEAT UNTIL you have checked all values and not found the value you are
4
looking for
Linear Search in Pseudocode
// Declare variables
DECLARE data : ARRAY[1:5] OF INTEGER
DECLARE target : INTEGER
DECLARE found : BOOLEAN
// Assign values to the array and target
data ← [5, 2, 8, 1, 9]
target ← 11
found ← FALSE // Start with the assumption that the target is not found
// Loop through each element in the array
FOR index ← 1 TO 5
// Check if the current element matches the target
IF data[index] = target THEN
found ← TRUE
OUTPUT "Target found"
ENDIF
NEXT index
// After the loop, check if the target was never found
IF found = FALSE THEN
OUTPUT "Target not found"
ENDIF
Linear Search in Python code
Page 13
Created by Turbolearn AI
# Identify the dataset to search, the target value and set the initial fla
data = [5, 2, 8, 1, 9]
target = 11
found = False
# Loop through each element in the data
for index in range(0, len(data)): # loop to go through all elements
# Check if the current element matches the target
if data[index] == target: # If found, output message
found = True
print("Target found")
break # Exit the loop if the target is found
# If the target is not found, output a message
if not found:
print("Target not found")
Bubble Sort
Sorting algorithms are precise step-by-step instructions that a computer
can follow to efficiently sort data in massive datasets.
A bubble sort is a simple sorting algorithm that starts at the beginning of
a dataset and checks values in 'pairs' and swaps them if they are not in
the correct order.
One full run of comparisons from beginning to end is called a 'pass'. A bubble sort
may require multiple 'passes' to sort the dataset. The algorithm is finished when
there are no more swaps to make.
How to Perform a Bubble Sort
Step Instruction
1 Compare the first two values in the dataset
2 IF they are in the wrong order... Swap them
3 Compare the next two values
4 REPEAT step 2 & 3 until you reach the end of the dataset (pass 1)
5 IF you have made any swaps... REPEAT from the start (pass 2,3,4...)
6 ELSE you have not made any swaps... STOP! the list is in the correct order
Page 14
Created by Turbolearn AI
Example
Perform a bubble sort on the following dataset
5 2 4 1 6 3
Step Instruction
1 Compare the first two values in the dataset 5 2 4 1 6 3
2 IF they are in the wrong order... Swap them 2 5 4 1 6 3
3 Compare the next two values 2 5 4 1 6 3
4 REPEAT step 2 & 3 until you reach the end of the dataset
5 & 4 SWAP! 2 4 5 1 6 3
5 & 1 SWAP! 2 4 1 5 6 3
5 & 6 NO SWAP! 2 4 1 5 6 3
6 & 3 SWAP! 2 4 1 5 3 6
IF you have made any swaps... REPEAT from the start (End of pass 2 (swaps
5
made)) 2 1 4 3 5 6
End of pass 3 (swaps made) 1 2 3 4 5 6
End of pass 4 (no swaps) 1 2 3 4 5 6
6 ELSE you have not made any swaps... STOP! the list is in the correct order
Bubble Sort in Pseudocode
Page 15
Created by Turbolearn AI
// Declare the array
DECLARE nums : ARRAY[1:11] OF INTEGER
nums ← [66, 7, 69, 50, 42, 80, 71, 321, 67, 8, 39]
// Store the length of the array
DECLARE numlength : INTEGER
numlength ← 11
// Set a flag to check if any swaps are made
DECLARE swaps : BOOLEAN
swaps ← TRUE
// Repeat the loop while swaps are being made
WHILE swaps = TRUE
swaps ← FALSE
// Loop through the array from the start to the second-last unsorted eleme
FOR y ← 1 TO numlength - 1
// If the current number is greater than the next number, swap them
IF nums[y] > nums[y + 1] THEN
DECLARE temp : INTEGER
temp ← nums[y]
nums[y] ← nums[y + 1]
nums[y + 1] ← temp
swaps ← TRUE // A swap was made
ENDIF
NEXT y
// Decrease the range as the last value is now sorted
numlength ← numlength - 1
ENDWHILE
// Output the sorted array
FOR i ← 1 TO 11
OUTPUT nums[i]
NEXT i
Bubble Sort in Python code
Page 16
Created by Turbolearn AI
# Unsorted dataset
nums = [66, 7, 69, 50, 42, 80, 71, 321, 67, 8, 39]
# Count the length of the dataset
numlength = len(nums)
# Set a flag to initiate the loop
swaps = True
while swaps: # While any swap is made, continue
swaps = False
# Loop through the dataset
for y in range(numlength - 1):
# Compare adjacent elements
if nums[y] > nums[y + 1]: # If the first number is bigger
# Swap the numbers using a temporary variable
nums[y], nums[y + 1] = nums[y + 1], nums[y]
swaps = True # Mark that a swap was made
# Each iteration confirms that the last element is in place
numlength -= 1
# Print the sorted list
print(nums)
Worked Example
A program uses a file to store a list of words. A sample of this data is shown
Milk Eggs Bananas Cheese Potatoes Grapes
Show the stages of a bubble sort when applied to data shown [2]
How to answer this question:
We need to sort the values into alphabetical order from A-Z You CAN use the first
letter of each word to simplify the process.
Answer
E, B, C, M, G, P (pass 1)
B, C, E, G, M, P (pass 2)
Other Standard Methods of a Solution
Page 17
Created by Turbolearn AI
Totalling
Totalling is keeping a running total of values entered into the algorithm.
An example may be totalling a receipt for purchases made at a shop.
In the example below, the total starts at 0 and adds up the user-inputted value for
each item in the list.
Total ← 0
FOR Count ← 1 TO ReceiptLength
INPUT ItemValue
Total ← Total + itemValue
NEXT Count
OUTPUT Total
Counting
Counting is when a count is incremented or decremented by a fixed value,
usually 1, each time it iterates. Counting keeps track of the number of
times an action has been performed.
Many algorithms use counting, including the linear search to track which element is
currently being considered.
In the example below, the count is incremented and each pass number is output until
fifty outputs have been produced.
Count ← 0
DO
OUTPUT “Pass number”, Count
Count ← Count + 1
UNTIL Count >= 50
In the example below, the count is decremented from fifty until the count reaches
zero. An output is produced for each pass.
Count ← 50
DO
OUTPUT “Pass number”, Count
Page 18
Created by Turbolearn AI
Maximum, Minimum & Average
Finding the largest (max), smallest (min), and average (mean) values in a list are
frequently used method in algorithms.
Examples could include:
Calculating the maximum and minimum student grades or scores in a game
Calculating the average grade of students in a class test
In the example below, in a list of student test scores, the highest, lowest, and
average scores are calculated and displayed to the screen.
Total ← 0
Scores ← [25, 11, 84, 91, 27]
Highest ← max(Scores)
Lowest ← min(Scores)
# Loop through the scores in the list (indexing starts from 0)
FOR Count ← 0 TO LENGTH(Scores) - 1
# Add score to total
Total ← Total + Scores[Count]
NEXT Count
# Calculate average
Average ← Total / LENGTH(Scores)
OUTPUT "The highest score is:", Highest
OUTPUT "The lowest score is:", Lowest
OUTPUT "The average score is:", Average
Validation & Verification
Validation
Validation is an automated process where a computer checks if a user
input is sensible and meets the program's requirements.
There are six categories of validation which can be carried out on fields and data
types:
Page 19
Created by Turbolearn AI
Range check
Length check
Type check
Presence check
Format check
Check digit
There can be occasions where more than one type of validation will be used on a
field. An example of this could be a password field which could have a length,
presence, and type check on it.
Range Check
Ensures the data entered as a number falls within a particular range.
Pseudocode
Ensures a percentage number is between 0-100 inclusive
OUTPUT “Enter a number between 0 and 100”
REPEAT
INPUT Number
IF Number < 0 OR Number > 100 THEN
OUTPUT “Number is not between 0 and 100, please try again”
ENDIF
UNTIL Number >= 0 AND Number <= 100
Python
Ensures a user's age has been entered and falls between the digits of 0−11
age = int(input("Enter your age"))
while age < 0 or age > 110:
age = int(input("Enter your age, ensure it is between 0-110"))
Length Check
Checks the length of a string.
Page 20
Created by Turbolearn AI
Pseudocode
Ensures a pin number can only contain 4 digits
OUTPUT “Please enter your 4 digit bank PIN number”
REPEAT
INPUT Pin
IF LENGTH(Pin) <> 4 THEN
OUTPUT “Your pin number must be four characters in length, please try
ENDIF
UNTIL LENGTH(Pin) ← 4
Python
Ensures a password is 8 characters or more
password_length = len(password)
while password_length < 8:
password = input("Enter a password which is 8 or more characters")
Type Check
Check the data type of a field.
Pseudocode
Ensures an age should be entered as an integer (whole number)
OUTPUT “Enter an integer number”
REPEAT
INPUT Number
IF Number <> DIV(Number, 1) THEN
OUTPUT “Not a whole number, please try again”
ENDIF
UNTIL Number ← DIV(Number , 1)
Python
Ensures an age should be entered as an integer (whole number)
age = input("Enter your age")
while [Link]() == False:
print("enter a number")
age = input("Enter your age as a number")
Presence Check
Looks to see if any data has been entered in a field.
Page 21
Created by Turbolearn AI
Pseudocode
Ensures username and password are both entered
OUTPUT “Enter your username”
REPEAT
INPUT Username
IF Username = “” THEN
OUTPUT “No username entered, please try again”
ENDIF
UNTIL Username <> “”
Python
Ensures when registering for a website the name field is not left blank
name = input("Enter your name")
while name == "":
name = input("You must enter your name here")
Format Check
Ensures that the data has been entered in the correct format.
Format checks are done using pattern matching and string handling.
Page 22
Created by Turbolearn AI
Pseudocode
Ensures a six digit ID number is entered against the format "XX9999" where X i
INPUT IDNumber
IF LENGTH(IDNumber) <> 6 THEN
OUTPUT "ID number must be 6 characters long"
END IF
ValidChars ← "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
FirstChar ← SUBSTRING(IDNumber, 1, 1)
ValidChar ← False
Index ← 1
WHILE Index <= LENGTH(ValidChars) AND ValidChar = False DO
IF FirstChar = ValidChars[Index] THEN
ValidChar ← True
ENDIF
Index ← Index + 1
ENDWHILE
IF ValidChar = False THEN
OUTPUT "First character is not a valid uppercase alphabetical character"
ENDIF
SecondChar ← SUBSTRING(IDNumber, 2, 2)
ValidChar ← False
Index ← 1
WHILE Index <= LENGTH(ValidChars) AND ValidChar = False DO
IF SecondChar = ValidChars[Index] THEN
ValidChar ← True
ENDIF
Index ← Index + 1
ENDWHILE
IF ValidChar = False THEN
OUTPUT "Second character is not a valid uppercase alphabetical character"
ENDIF
Digits ← INT(SUBSTRING(IDNumber, 3, 6))
IF Digits < 0000 OR Digits > 9999 THEN
OUTPUT "Digits invalid. Enter four valid digits in the range 0000-9999"
ENDIF
```## Data Validation and Verification
### Validation Checks
**Validation** is the process of ensuring that the data entered is possible, r
> A range check is a type of validation that tests whether the data entered fa
Example of validation check:
* **Range Check**: Checks that data entered fits within specified values.
### Verification Checks
Page 23
Created by Turbolearn AI
**Verification** is the process of checking that data is accurate when entered
> Double entry checking involves entering the data twice in separate input box
Verification methods include:
* Double entry checking
* Visual checks
#### Double Entry Checking Pseudocode
REPEAT OUTPUT “Enter your password” INPUT Password OUTPUT “Please confirm
your password” INPUT ConfirmPassword IF Password <> ConfirmPassword THEN
OUTPUT “Passwords do not match, please try again” ENDIF UNTIL Password =
ConfirmPassword
#### Visual Checks Pseudocode
REPEAT OUTPUT “Enter your name” INPUT Name OUTPUT “Your name is: “, Name,
“. Is this correct? (y/n)” INPUT Answer UNTIL Answer = “y”
Page 24
Created by Turbolearn AI
### Worked Example: Validation vs. Verification
| Check Type | Description
| :----------- | :------------------------------------------------------------
| Validation | To test if the data entered is possible / reasonable / sensib
| Verification | To test if the data input is the same as the data that was in
## Suitable Test Data
### Types of Test Data
**Suitable test data** is specifically chosen to test the functionality of a p
* Normal
* Abnormal
* Extreme
* Boundary
#### Python Example
```python
# Ask for user's name
name = input("What is your name? ")
# Ask for user's age
age = int(input("How old are you? "))
# Check if age is between 12 and 18
if age >= 12 and age <= 18:
print("Welcome, " + name + "! Your age is accepted.")
else:
print("Sorry, " + name + ". Your age is not accepted.")
Normal data: Data that should be accepted by the program (e.g., entering 14 as
age).
Abnormal data: Data that is the wrong data type (e.g., entering "H" as age).
Extreme data: Maximum and minimum values of normal data that are accepted
(e.g., entering 12 or 18 as age).
Boundary data: Values on either side of the maximum and minimum values are
tested, including the largest and smallest acceptable/unacceptable values (e.g.,
entering 11 or 19 as age).
Test Data Table Example
Page 25
Created by Turbolearn AI
Type of Test Input Expected Output
Normal 14 Accepted
Normal 16 Accepted
Extreme 12 Accepted
Extreme 18 Accepted
Abnormal H Rejected
Abnormal @ Rejected
Boundary 11 Rejected
Boundary 19 Rejected
Worked Example: Price Check
Value Type Expected Outcome
10.00 Boundary or abnormal data Rejected as it is out of range
9.99 Boundary, extreme, and normal data Accepted as it is within the normal range
"Ten" Abnormal data Rejected as it is the wrong value type
Trace Tables
What is a Trace Table?
A trace table is used to test algorithms and programs for logic errors that appear
when an algorithm or program executes.
Trace tables can be used to:
Discover the purpose of an algorithm
Record the state of the algorithm at each step or iteration
Each stage of the algorithm is executed step by step. Inputs, outputs, variables, and
processes can be checked for the correct value when the stage is completed.
Trace Table Walkthrough Example
Here's an example of a flowchart to determine the highest number of ten user-
entered numbers, followed by a trace table.
Page 26
Created by Turbolearn AI
The flowchart begins by initializing a count to 1 and prompting the user to enter ten
numbers, storing the first number as the "Highest" value. It then enters a loop,
updating the "Highest" value if a larger number is entered.
Example test data: 4, 3, 7, 1, 8, 3, 6, 9, 12, 10
Trace Table:
Page 27
Created by Turbolearn AI
Count Number Highest Output
1 4 4 Enter ten numbers
2 3 4 Enter your first number
3 7 7 Enter your next number
4 1 7
5 8 8
6 3 8
7 6 8
8 9 9
9 12 12
10 10 12 12 is your highest number
Worked Example: Algorithm Termination
Here's an example of a flowchart and trace table, where the algorithm terminates if
-1 is entered.
Page 28
Created by Turbolearn AI
The flowchart begins with a "START" oval and proceeds to prompt for an "INPUT
Value". The flowchart then navigates through a series of conditional statements and
calculations, ultimately leading to one of three possible output outcomes: "OUTPUT
'Reject; Abnormal'", "OUTPUT 'Accept; Normal'", or "OUTPUT 'Accept; Extreme'".
Input Data: 50, 75, 99, 28, 82, 150, -1, 672, 80
Trace Table:
Value Di1 Di2 Output
50 50 0 Accept: Extreme
75 25 25 Accept: Normal
99 1 49 Accept: Normal
28 Reject: Abnormal
82 18 32 Accept: Normal
150 Reject: Abnormal
-1
Identifying Errors
Categories of Errors
When designing algorithms, programmers must be able to identify and fix three main
categories of errors:
Syntax errors
Logic errors
Runtime errors
When describing an error:
Use “prevents the program from running” for syntax
Use “produces incorrect output” for logic
Use “causes the program to crash” for runtime
Syntax Errors
Page 29
Created by Turbolearn AI
A syntax error is an error that breaks the grammatical rules of a programming
language and stops it from running.
Examples of syntax errors are:
Typos and spelling errors
Missing or extra brackets or quotes
Misplaced or missing semicolons
Invalid variable or function names
Incorrect use of operators
Incorrectly nested loops & blocks of code
Python Code - With Syntax Errors
def generate_username(first_name, last_name)
username = f"{first_name[0]}{last_name[0]}{last_name[:3]}"
return username
def main():
# --------------------------------------------------------------------
# Prompts the user for personal information and displays a suggested u
# --------------------------------------------------------------------
first_name = imput("Enter your first name: ")
last_name = input("Enter your last name: ")
usdrname = generate_username(first_name, last_name)
print(f"Here's a suggested username: {username}")
# --------------------------------------------------------------------
# Main program
# --------------------------------------------------------------------
main
Python Code - Without Syntax Errors
Page 30
Created by Turbolearn AI
def generate_username(first_name, last_name):
username = f"{first_name[0]}{last_name[0]}{last_name[:3]}"
return username
def main():
# --------------------------------------------------------------------
# Prompts the user for personal information and displays a suggested u
# --------------------------------------------------------------------
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
username = generate_username(first_name, last_name)
print(f"Here's a suggested username: {username}")
# --------------------------------------------------------------------
# Main program
# --------------------------------------------------------------------
main()
Logic Errors
A logic error is where incorrect code is used that causes the program to run, but
produces an incorrect output or result.
Examples of logic errors are:
Incorrect use of operators (< and >)
Logical operator confusion (AND for OR)
Looping one extra time
Indexing arrays incorrectly (arrays indexing starts from 0)
Using variables before they are assigned
Infinite loops
Python Code Example
Page 31
Created by Turbolearn AI
def calculate_area(length, width):
### Calculates the area of a rectangle
# Inputs: length (float): The length of the rectangle (positive value)
# width (float): The width of the rectangle (positive value)
# Returns: float: The calculated area of the rectangle
# Raises: ValueError: If either length or width is non-positive
###
if length < 0 or width < 0:
raise ValueError("Length and width must be positive values.")
area = length * width
return area
def main():
# --------------------------------------------------------------------
# Prompts the user for rectangle dimensions and prints the calculated
# --------------------------------------------------------------------
try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
# Call the area calculation function
area = calculate_area(length, width)
print(f"The area of the rectangle is approximately {area:.2f} squa
except ValueError as error:
print(f"Error: {error}")
# --------------------------------------------------------------------
# Main program
# --------------------------------------------------------------------
main()
Logic Error Test Table
Changes
Test
Test data Expected outcome Actual outcome needed?
number
(Y/N)
"The area of the "The area of the
Length =
rectangle is rectangle is
1 5 Width = N
approximately 25 approximately 25.00
5
square units." square units."
"The area of the
Length =
"Length and width must rectangle is
2 10 Width Y
be positive values." approximately 0.00
=0
square units."
Page 32
Created by Turbolearn AI
Logic error located on line if length < 0 or width < 0:
Logic error identified in expression < 0, should be <= 0 so that 0 is not accepted
as valid input for length or width
Runtime Errors
A runtime error is an error that causes a program to crash.
Examples of runtime errors are:
Dividing a number by 0
Index out of the range of an array
Unable to read or write a drive
Python Code Example
The image displays a Python code snippet for calculating the area of a rectangle.
Runtime Error Test Table
Page 33
Created by Turbolearn AI
Changes
Test
Test data Expected outcome Actual outcome needed?
number
(Y/N)
"The area of the "The area of the
Length =
rectangle is rectangle is
1 10 Width N
approximately 100 approximately 100.00
= 10
square units." square units."
Length = "Program could not
2 "abc" convert string to float, Program crashed Y
Width = 0 try again"
Runtime error located in the try block.
Runtime error identified as missing iteration (while loop) so program does not
ask user to enter width and height again
Corrected code includes a while loop:
while True:
try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
# Call the area calculation function
area = calculate_area(length, width)
print(f"The area of the rectangle is approximately {area:.2f} squa
break # Exit the loop if successful
except ValueError as error:
print(f"Error: {error}")
print("Please enter positive values for length and width.")
Algorithmic Thinking
What is Algorithmic Thinking?
Algorithmic thinking is the process of creating step-by-step instructions in order to
produce a solution to a problem.
Algorithmic thinking requires the use of abstraction and decomposition to identify
each individual step. Once each step has been identified, a precise set of rules
(algorithm) can be created and the problem will be solved.
Page 34
Created by Turbolearn AI
An example of algorithmic thinking is following a recipe; if the recipe is
followed precisely, it should lead to the desired outcome. A set of traffic
lights is an example of how algorithmic thinking can lead to solutions
being automated.
Page 35