FORM 5 COMPUTER SCIENCE
Complete Study Guide
Algorithms, Programming & Databases
ZIMSEC A-Level Syllabus Aligned
Comprehensive Coverage with 10+ Examples, Exercises & Exam Practice
PART 1: ALGORITHMS
1.1 Introduction to Pseudocode
Pseudocode is a simplified, informal way of describing programming concepts without
using any specific programming language syntax. It uses human-readable statements to
represent algorithmic logic.
Key Pseudocode Constructs:
SEQUENCE: Instructions executed in order
SELECTION: IF-THEN-ELSE decisions
ITERATION: FOR, WHILE, REPEAT loops
Example 1: Simple Sequence Algorithm
Problem: Calculate the area of a rectangle given its length and width.
ALGORITHM CalculateRectangleArea
INPUT: length, width
OUTPUT: area
BEGIN
DISPLAY "Enter the length:"
INPUT length
DISPLAY "Enter the width:"
INPUT width
area ← length × width
DISPLAY "The area is: ", area
END
Explanation: This algorithm uses a simple sequence structure. It takes two inputs (length
and width), performs multiplication to calculate the area, and displays the result. The
algorithm follows a top-to-bottom execution flow with no decisions or loops.
Step 1: User enters length (e.g., 5)
Step 2: User enters width (e.g., 3)
Step 3: area ← 5 × 3 = 15
Step 4: Display "The area is: 15"
Example 2: IF-THEN Selection Structure
Problem: Determine if a student passed or failed based on their score.
ALGORITHM CheckPassStatus
INPUT: score
OUTPUT: pass/fail status
BEGIN
DISPLAY "Enter student score (0-100):"
INPUT score
IF score >= 50 THEN
DISPLAY "PASS - Congratulations!"
DISPLAY "Student has met the pass requirement."
ELSE
DISPLAY "FAIL - Needs improvement."
DISPLAY "Student must re-take the assessment."
ENDIF
DISPLAY "End of grading."
END
Explanation: This algorithm demonstrates selection using IF-THEN-ELSE. The decision
structure checks if the score is 50 or above. If true, the pass message is displayed;
otherwise, the fail message is shown. The "End of grading" message displays regardless of
the condition.
The condition (score >= 50) evaluates to TRUE or FALSE
Only ONE branch executes based on the condition
ELSE is optional but provides alternative action
Example 3: Nested IF-THEN-ELSE
Problem: Classify a student's grade (A, B, C, D, F).
ALGORITHM ClassifyGrade
INPUT: score
OUTPUT: letter grade
BEGIN
DISPLAY "Enter the score:"
INPUT score
IF score >= 80 THEN
grade ← "A"
DISPLAY "Excellent work!"
ELSE IF score >= 70 THEN
grade ← "B"
DISPLAY "Good performance!"
ELSE IF score >= 60 THEN
grade ← "C"
DISPLAY "Satisfactory."
ELSE IF score >= 50 THEN
grade ← "D"
DISPLAY "Needs improvement."
ELSE
grade ← "F"
DISPLAY "Failed. Please retake."
ENDIF
DISPLAY "Final Grade: ", grade
END
Explanation: This shows cascading/nested IF-ELSE structures. Conditions are checked in
order from highest to lowest. Once a condition is TRUE, its corresponding grade is assigned
and remaining conditions are skipped (efficient execution).
Example 4: FOR Loop Iteration
Problem: Display numbers 1 to 10.
ALGORITHM DisplayNumbers1to10
OUTPUT: numbers 1 through 10
BEGIN
FOR counter ← 1 TO 10 DO
DISPLAY counter
ENDFOR
DISPLAY "Counting complete!"
END
Explanation: The FOR loop repeats a block of code a specific number of times. The loop
variable (counter) starts at 1 and increments by 1 each iteration until it reaches 10. The
loop body executes exactly 10 times.
Trace Table:
Iteration counter Output Action
1 1 1 Display 1
2 2 2 Display 2
... ... ... ...
10 10 10 Display 10
After loop 11 - Exit and display
completion
Example 5: WHILE Loop
Problem: Calculate the sum of numbers until user enters 0.
ALGORITHM SumUntilZero
OUTPUT: sum of all entered numbers
BEGIN
sum ← 0
number ← 1
WHILE number ≠ 0 DO
DISPLAY "Enter a number (0 to stop):"
INPUT number
IF number ≠ 0 THEN
sum ← sum + number
ENDIF
ENDWHILE
DISPLAY "The total sum is: ", sum
END
Explanation: WHILE loops repeat as long as a condition is TRUE. The condition is checked
BEFORE each iteration. Here, the loop continues until the user enters 0. This is a pre-test
loop (condition checked first).
Example 6: REPEAT-UNTIL Loop
Problem: Get a valid menu choice (1-4) from user.
ALGORITHM GetValidMenuChoice
OUTPUT: valid menu choice
BEGIN
REPEAT
DISPLAY "Main Menu:"
DISPLAY "1. New Game"
DISPLAY "2. Load Game"
DISPLAY "3. Settings"
DISPLAY "4. Exit"
DISPLAY "Enter your choice (1-4):"
INPUT choice
IF choice < 1 OR choice > 4 THEN
DISPLAY "Invalid choice. Please try again."
ENDIF
UNTIL choice >= 1 AND choice <= 4
DISPLAY "You selected option ", choice
END
Explanation: REPEAT-UNTIL is a post-test loop that executes at least once before checking
the condition. The loop continues UNTIL the condition becomes TRUE. This ensures the
user is always prompted at least once before validation.
Example 7: Linear Search Algorithm
Problem: Find a target value in an unsorted array using linear search.
ALGORITHM LinearSearch
INPUT: array[1..n], target
OUTPUT: position of target or -1 if not found
BEGIN
position ← -1 // Not found flag
found ← FALSE
FOR i ← 1 TO n DO
IF array[i] = target THEN
position ← i
found ← TRUE
EXIT FOR // Stop searching once found
ENDIF
ENDFOR
IF found = TRUE THEN
DISPLAY "Found at position ", position
ELSE
DISPLAY "Not found in the array."
ENDIF
RETURN position
END
Explanation: Linear search checks each element sequentially from the beginning until the
target is found or the array ends. It works on both sorted and unsorted arrays. Time
complexity: O(n) - worst case checks all n elements.
Trace Example: array = [23, 45, 12, 67, 89, 34], target = 67
i=1: 23 ≠ 67, continue
i=2: 45 ≠ 67, continue
i=4: 67 = 67 ✓ FOUND at position 4
i=3: 12 ≠ 67, continue
Example 8: Binary Search Algorithm
Problem: Find a target value in a sorted array using binary search.
ALGORITHM BinarySearch
INPUT: sorted_array[1..n], target
OUTPUT: position of target or -1 if not found
BEGIN
first ← 1
last ← n
found ← FALSE
position ← -1
WHILE first <= last AND found = FALSE DO
middle ← (first + last) DIV 2
IF sorted_array[middle] = target THEN
position ← middle
found ← TRUE
ELSE IF sorted_array[middle] > target THEN
last ← middle - 1 // Search left half
ELSE
first ← middle + 1 // Search right half
ENDIF
ENDWHILE
IF found = TRUE THEN
DISPLAY "Found at position ", position
ELSE
DISPLAY "Not found in the array."
ENDIF
RETURN position
END
Explanation: Binary search repeatedly divides a SORTED array in half to locate the target. It
compares the target with the middle element and eliminates half the remaining elements
each iteration. Time complexity: O(log n).
Trace Example: sorted_array = [12, 23, 34, 45, 56, 67, 78, 89], target = 67
Iteration 2: first=5, last=8, middle=6, array[6]=67 = 67 ✓ FOUND at position 6
Iteration 1: first=1, last=8, middle=4, array[4]=45 < 67, first=5
Total iterations: 2 (vs 6 for linear search!)
Example 9: Bubble Sort Algorithm
Problem: Sort an array of numbers in ascending order using bubble sort.
ALGORITHM BubbleSort
INPUT: array[1..n]
OUTPUT: sorted array in ascending order
BEGIN
FOR pass ← 1 TO n-1 DO
FOR i ← 1 TO n - pass DO
IF array[i] > array[i+1] THEN
// Swap elements
temp ← array[i]
array[i] ← array[i+1]
array[i+1] ← temp
ENDIF
ENDFOR
ENDFOR
DISPLAY "Sorted array:"
FOR i ← 1 TO n DO
DISPLAY array[i]
ENDFOR
END
Explanation: Bubble sort repeatedly steps through the list, compares adjacent elements, and
swaps them if they're in the wrong order. After each pass, the largest unsorted element
"bubbles up" to its correct position. Time complexity: O(n²).
Trace Example: [64, 34, 25, 12, 22, 11, 90]
Pass 1: [34, 25, 12, 22, 11, 64, 90] - 90 bubbled to end
Pass 2: [25, 12, 22, 11, 34, 64, 90] - 64 in position
Pass 3: [12, 22, 11, 25, 34, 64, 90]
Pass 5: [11, 12, 22, 25, 34, 64, 90] ✓ Sorted
Pass 4: [12, 11, 22, 25, 34, 64, 90]
Example 10: Quick Sort Algorithm
Problem: Sort an array using the divide-and-conquer quick sort approach.
ALGORITHM QuickSort
INPUT: array[low..high]
OUTPUT: sorted array
BEGIN
IF low < high THEN
pivot_index ← Partition(array, low, high)
QuickSort(array, low, pivot_index - 1)
QuickSort(array, pivot_index + 1, high)
ENDIF
END
FUNCTION Partition(array, low, high)
pivot ← array[high] // Choose last element as pivot
i ← low - 1
FOR j ← low TO high - 1 DO
IF array[j] <= pivot THEN
i ← i + 1
SWAP array[i], array[j]
ENDIF
ENDFOR
SWAP array[i+1], array[high]
RETURN i + 1
END FUNCTION
Explanation: Quick sort uses a divide-and-conquer strategy. It picks a pivot element and
partitions the array around the pivot, placing smaller elements left and larger elements
right. It then recursively sorts the sub-arrays. Average time complexity: O(n log n).
Trace Example: [10, 7, 8, 9, 1, 5]
Initial: pivot=5, partition around 5
Left partition: [1], Right partition: [10, 7, 8, 9]
Continue recursively...
Final sorted: [1, 5, 7, 8, 9, 10]
Example 11: Array Input and Processing
Problem: Read 10 integers into an array and calculate their sum and average.
ALGORITHM ArraySumAndAverage
INPUT: 10 integers
OUTPUT: sum and average of the integers
BEGIN
DECLARE numbers[1..10] AS INTEGER
sum ← 0
// Input phase
FOR i ← 1 TO 10 DO
DISPLAY "Enter number ", i, ":"
INPUT numbers[i]
ENDFOR
// Processing phase
FOR i ← 1 TO 10 DO
sum ← sum + numbers[i]
ENDFOR
average ← sum / 10
// Output phase
DISPLAY "The sum is: ", sum
DISPLAY "The average is: ", average
RETURN sum, average
END
Explanation: This algorithm demonstrates complete array processing. The first loop inputs
10 numbers into the array. The second loop traverses the array to calculate the sum. Finally,
the average is computed by dividing the sum by 10.
Example 12: Finding Maximum and Minimum in Array
Problem: Find the maximum and minimum values in an array.
ALGORITHM FindMaxMin
INPUT: array[1..n]
OUTPUT: maximum and minimum values
BEGIN
max_val ← array[1] // Assume first element is max
min_val ← array[1] // Assume first element is min
FOR i ← 2 TO n DO
IF array[i] > max_val THEN
max_val ← array[i] // Update max
ENDIF
IF array[i] < min_val THEN
min_val ← array[i] // Update min
ENDIF
ENDFOR
DISPLAY "Maximum value: ", max_val
DISPLAY "Minimum value: ", min_val
RETURN max_val, min_val
END
Explanation: The algorithm starts by assuming the first element is both maximum and
minimum. It then iterates through the remaining elements, updating the max_val and
min_val whenever a larger or smaller value is found. This single-pass approach is efficient
with O(n) complexity.
1.2 Exercises: Algorithms
Exercise 1: Simple Interest Calculation
Write an algorithm to calculate simple interest given principal, rate, and time.
Formula: Simple Interest = (Principal × Rate × Time) / 100
Exercise 2: Grade Classification
Write an algorithm that reads a student's score and displays:
"Distinction" if score >= 75
"Credit" if score >= 60
"Pass" if score >= 50
"Fail" if score < 50
Exercise 3: Sum of Even Numbers
Write an algorithm using a WHILE loop to calculate the sum of all even numbers from 1 to
100.
Exercise 4: Binary Search Trace
Trace the binary search algorithm step by step for:
Array: [5, 12, 18, 25, 33, 42, 56, 68, 79, 90]
Target: 42
Exercise 5: Bubble Sort Trace
Show all passes of bubble sort for the array: [38, 27, 43, 3, 9, 82, 10]
ANSWERS
Answer 1: Simple Interest Calculation
ALGORITHM CalculateSimpleInterest
INPUT: principal, rate, time
OUTPUT: simple interest
BEGIN
DISPLAY "Enter Principal:"
INPUT principal
DISPLAY "Enter Rate (%):"
INPUT rate
DISPLAY "Enter Time (years):"
INPUT time
simple_interest ← (principal × rate × time) / 100
DISPLAY "Simple Interest = ", simple_interest
RETURN simple_interest
END
Answer 2: Grade Classification
ALGORITHM ClassifyGrade
INPUT: score
OUTPUT: grade classification
BEGIN
DISPLAY "Enter student score:"
INPUT score
IF score >= 75 THEN
DISPLAY "Distinction"
ELSE IF score >= 60 THEN
DISPLAY "Credit"
ELSE IF score >= 50 THEN
DISPLAY "Pass"
ELSE
DISPLAY "Fail"
ENDIF
END
Answer 3: Sum of Even Numbers
ALGORITHM SumEvenNumbers
OUTPUT: sum of even numbers from 1 to 100
BEGIN
sum ← 0
number ← 2
WHILE number <= 100 DO
sum ← sum + number
number ← number + 2
ENDWHILE
DISPLAY "Sum of even numbers 1-100: ", sum
RETURN sum
END
// Result: 2550
Answer 4: Binary Search Trace
Array: [5, 12, 18, 25, 33, 42, 56, 68, 79, 90], Target: 42
Step 1: first=1, last=10, middle=5, array[5]=33 < 42, first=6
Step 3: first=6, last=7, middle=6, array[6]=42 = 42 ✓ FOUND at position 6
Step 2: first=6, last=10, middle=8, array[8]=68 > 42, last=7
Answer 5: Bubble Sort Trace
Array: [38, 27, 43, 3, 9, 82, 10]
Pass 1: [27, 38, 3, 9, 43, 10, 82]
Pass 2: [27, 3, 9, 38, 10, 43, 82]
Pass 4: [3, 9, 10, 27, 38, 43, 82] ✓ Sorted
Pass 3: [3, 9, 27, 10, 38, 43, 82]
PART 2: PROGRAMMING FUNDAMENTALS
2.1 High-Level Programming Concepts
High-level programming languages provide abstraction from machine code, making
programs easier to write, read, and maintain. Examples include Python, Java, [Link], and
C++.
Key Features of High-Level Languages:
Readability: Code resembles human language
Portability: Can run on different hardware
Abstraction: Hides complex hardware details
Rich libraries: Pre-written code for common tasks
Example 1: Variable Declaration and Initialization (Python)
# Integer variables - whole numbers
student_age = 17 # Integer (int)
number_of_subjects = 5 # Integer (int)
# Float variables - decimal numbers
student_height = 1.65 # Float (floating-point)
average_score = 75.5 # Float
# String variables - text data
student_name = "John Smith"
student_id = "S2024001" # String (text)
# Boolean variables - True/False values
is_enrolled = True # Boolean
has_paid_fees = False # Boolean
# Displaying variables
print("Student Name:", student_name)
print("Student Age:", student_age)
print("Average Score:", average_score)
print("Enrolled Status:", is_enrolled)
# Demonstrating type conversion
student_age = int("18") # String to integer
total_marks = float(95) # Integer to float
Explanation: Variables are named storage locations that hold data. Different data types
serve different purposes:
INT/Integer: Stores whole numbers (17, 100, -5)
FLOAT/Real: Stores decimal numbers (1.65, 3.14, -0.5)
STRING/Text: Stores sequences of characters
BOOLEAN: Stores True or False values
Example 2: User Input and Output Operations (Python)
# Display messages to user
print("==================================")
print(" RETAIL PURCHASE CALCULATOR ")
print("==================================")
# Taking numeric input from user
item_price = float(input("Enter item price: $"))
quantity = int(input("Enter quantity: "))
# Taking string input
customer_name = input("Enter your name: ")
# Processing
subtotal = item_price * quantity
tax_rate = 0.15 # 15% tax
tax_amount = subtotal * tax_rate
total_cost = subtotal + tax_amount
# Formatted output
print("\n--- RECEIPT ---")
print(f"Customer: {customer_name}")
print(f"Item Price: ${item_price:.2f}")
print(f"Quantity: {quantity}")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (15%): ${tax_amount:.2f}")
print("-" * 20)
print(f"TOTAL: ${total_cost:.2f}")
Explanation: Input/Output operations are fundamental to interactive programs:
print(): Displays output to the console
input(): Reads input from the user (returns string)
Type conversion (int(), float()): Converts input to required types
Example 3: IF-THEN-ELSE Conditional Logic (Python)
def calculate_shipping(order_total):
"""
Calculate shipping based on order total:
- Orders over $100: FREE shipping
- Orders $50-$100: $5.99 shipping
- Orders under $50: $9.99 shipping
"""
if order_total > 100:
shipping_cost = 0.00
shipping_type = "FREE"
elif order_total >= 50:
shipping_cost = 5.99
shipping_type = "Standard"
else:
shipping_cost = 9.99
shipping_type = "Express"
return shipping_cost, shipping_type
# Main program
print("SHIPPING COST CALCULATOR")
print("=" * 30)
order_amount = float(input("Enter order total: $"))
shipping, ship_type = calculate_shipping(order_amount)
total_with_shipping = order_amount + shipping
print(f"\nOrder Total: ${order_amount:.2f}")
print(f"Shipping ({ship_type}): ${shipping:.2f}")
print(f"Final Total: ${total_with_shipping:.2f}")
Explanation: IF-ELSE statements control program flow based on conditions:
IF condition is TRUE: execute first block
ELIF (else if): check another condition if previous was FALSE
ELSE: executes if all previous conditions were FALSE
Comparisons: >, <, >=, <=, ==, !=
Example 4: FOR Loop with Range (Python)
def multiplication_table(number, rows=10):
"""Generate multiplication table for given number"""
print(f"\n--- Multiplication Table for {number} ---")
print("-" * 30)
for i in range(1, rows + 1):
product = number * i
print(f"{number} x {i:2d} = {product:3d}")
def sum_of_numbers(n):
"""Calculate sum of 1 to n using FOR loop"""
total = 0
for i in range(1, n + 1):
total += i
return total
def factorial(n):
"""Calculate factorial n! using FOR loop"""
result = 1
for i in range(1, n + 1):
result *= i
return result
# Main program
num = int(input("Enter number for multiplication table: "))
multiplication_table(num)
print(f"\nSum of 1 to 10: {sum_of_numbers(10)}")
print(f"5! = {factorial(5)}") # Output: 120
Explanation: FOR loops iterate a specific number of times:
range(start, stop): generates sequence from start to stop-1
range(stop): starts from 0 by default
Nested loops: loop inside another loop
Example 5: WHILE Loop with Counter (Python)
import random
def guessing_game():
"""Number guessing game with limited attempts"""
secret_number = [Link](1, 100)
max_attempts = 7
print("=" * 40)
print(" GUESS THE NUMBER GAME!")
print("=" * 40)
print(f"I'm thinking of a number between 1 and 100.")
print(f"You have {max_attempts} attempts to guess it.")
print("=" * 40)
attempts = 0
has_won = False
while attempts < max_attempts:
try:
guess = int(input("\nEnter your guess: "))
except ValueError:
print("Please enter a valid number!")
continue
attempts += 1
remaining = max_attempts - attempts
if guess == secret_number:
print(f"\nCORRECT! You got it in {attempts} attempts!")
has_won = True
break
elif guess < secret_number:
print(f"Too low! {remaining} attempts remaining.")
else:
print(f"Too high! {remaining} attempts remaining.")
if not has_won:
print(f"\nGame Over! The number was {secret_number}.")
return has_won, attempts
guessing_game()
Explanation: WHILE loops continue until a condition becomes FALSE:
Condition is checked BEFORE each iteration (pre-test loop)
Must ensure the condition eventually becomes FALSE (avoid infinite loops)
break: exits loop immediately
continue: skips to next iteration
Example 6: Arrays (Lists) in Python
def array_operations():
"""Demonstrate list operations"""
# Creating arrays/lists
student_names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
test_scores = [85, 92, 78, 95, 88]
# Accessing elements (0-indexed)
print(f"First student: {student_names[0]}")
print(f"Second score: {test_scores[1]}")
# Negative indexing (from end)
print(f"Last student: {student_names[-1]}")
# Slicing arrays
print(f"First 3: {student_names[0:3]}")
print(f"Last 2: {student_names[-2:]}")
# Modifying elements
student_names[2] = "Charlotte"
test_scores[0] += 5
# List methods
student_names.append("Frank")
student_names.insert(1, "George")
student_names.remove("Eve")
deleted = student_names.pop()
# Finding length
print(f"Number of students: {len(student_names)}")
def two_dimensional_array():
"""Demonstrate 2D arrays (matrices)"""
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
element = matrix[1][2] # Row 1, Column 2 = 6
print("\nMatrix:")
for row in matrix:
for element in row:
print(element, end=" ")
print()
array_operations()
two_dimensional_array()
Explanation: Lists are dynamic arrays in Python:
Indexing starts at 0 (first element), not 1
Negative indexing accesses from the end (-1 = last)
append(): adds element to the end
insert(): adds at specific position
remove(): removes by value, pop(): removes by index
Example 7: Functions and Procedures (Python)
# Function with parameters and return value
def calculate_simple_interest(principal, rate, time):
"""Calculate simple interest"""
interest = (principal * rate * time) / 100
return interest
# Procedure (no return value)
def display_account_info(name, balance):
"""Display formatted account information"""
print("\n" + "=" * 30)
print(f" ACCOUNT: {name}")
print("=" * 30)
print(f"Current Balance: ${balance:,.2f}")
print("=" * 30)
# Function with default parameters
def apply_discount(price, discount_percent=10):
"""Apply discount to price"""
discount_amount = price * (discount_percent / 100)
final_price = price - discount_amount
return final_price, discount_amount
# Function with multiple return values
def calculate_loan_approval(income, expenses, debt):
"""Calculate debt-to-income ratio"""
ratio = (debt / income) * 100 if income > 0 else float('inf')
if expenses > income:
return False, ratio, "Expenses exceed income!"
elif ratio > 40:
return False, ratio, "Debt ratio too high (>40%)"
else:
return True, ratio, "Loan approved!"
# Main program
principal = float(input("Enter principal: $"))
rate = float(input("Enter annual rate (%): "))
time = float(input("Enter time (years): "))
interest = calculate_simple_interest(principal, rate, time)
total = principal + interest
print(f"\nSimple Interest: ${interest:,.2f}")
print(f"Total Amount: ${total:,.2f}")
Explanation: Functions are reusable blocks of code:
def keyword defines a function
Parameters: inputs the function receives
return: sends a value back to caller
Default parameters: used when argument not provided
Example 8: File Input and Output (Python)
import os
def write_student_records(filename="[Link]"):
"""Write student records to a text file"""
with open(filename, 'w') as file:
[Link]("STUDENT RECORDS - Generated by System\n")
[Link]("=" * 40 + "\n")
n = int(input("Number of students: "))
for i in range(n):
print(f"\n--- Student {i+1} ---")
student_id = input("ID: ")
name = input("Name: ")
score = input("Score: ")
[Link](f"{student_id},{name},{score}\n")
print(f"\nRecords saved to {filename}")
def read_student_records(filename="[Link]"):
"""Read and display student records from file"""
if not [Link](filename):
print(f"File {filename} not found!")
return []
students = []
with open(filename, 'r') as file:
header1 = [Link]()
header2 = [Link]()
print("\n" + "=" * 50)
print(" RETRIEVED STUDENT RECORDS")
print("=" * 50)
for line in file:
line = [Link]()
if line:
parts = [Link](',')
if len(parts) == 3:
student_id, name, score = parts
[Link]({
'id': student_id,
'name': name,
'score': float(score)
})
print(f"{student_id:10} | {name:20} | {score:6}")
return students
write_student_records()
read_student_records()
Explanation: File handling allows programs to store data permanently:
open(filename, "w"): Opens file for writing (creates/overwrites)
open(filename, "r"): Opens file for reading
open(filename, "a"): Opens file for appending
with statement: Automatically closes file
Example 9: Nested Loops and 2D Arrays (Python)
def create_grade_book():
"""Create a grade book with multiple students and subjects"""
grade_book = [
[85, 92, 78, 88], # Student 1
[90, 85, 95, 82], # Student 2
[77, 88, 72, 90] # Student 3
]
subjects = ["Math", "English", "Science", "History"]
students = ["Alice", "Bob", "Charlie"]
print("=" * 70)
print(" GRADE BOOK")
print("=" * 70)
print(f"{'Student':<12}", end=" ")
for subject in subjects:
print(f"{subject:<12}", end=" ")
print("Average")
print("-" * 70)
for i in range(3):
total = 0
print(f"{students[i]:<12}", end=" ")
for j in range(4):
grade = grade_book[i][j]
total += grade
print(f"{grade:<12}", end=" ")
average = total / 4
print(f"{average:.2f}")
print("=" * 70)
def pattern_nested_loops():
"""Generate various patterns using nested loops"""
print("\n--- Pattern: Right Triangle ---")
for i in range(1, 6):
for j in range(1, i + 1):
print("*", end=" ")
print()
create_grade_book()
pattern_nested_loops()
Explanation: Nested loops are loops inside other loops:
Outer loop controls the number of iterations of inner loop
2D arrays require nested loops to traverse all elements
Common pattern: O(n²) complexity for square traversal
Example 10: String Manipulation (Python)
def string_operations_demo():
"""Demonstrate various string operations"""
text = "Hello, World!"
print(f"Original: {text}")
print(f"First char: {text[0]}")
print(f"Last char: {text[-1]}")
print(f"Characters 0-4: {text[0:5]}")
print(f"Uppercase: {[Link]()}")
print(f"Lowercase: {[Link]()}")
print(f"Replace: {[Link]('World', 'Python')}")
print(f"Split: {[Link](',')}")
print(f"Length: {len(text)}")
def palindrome_checker():
"""Check if a string is a palindrome"""
text = input("Enter text to check: ").lower().replace(" ", "")
is_palindrome = text == text[::-1]
if is_palindrome:
print(f"'{text}' is a PALINDROME!")
else:
print(f"'{text}' is NOT a palindrome.")
return is_palindrome
def text_analyzer():
"""Analyze text: count words, vowels, consonants"""
text = input("Enter text to analyze: ")
cleaned = ""
for char in [Link]():
if [Link]() or char == ' ':
cleaned += char
words = [Link]()
vowels = 'aeiou'
vowel_count = sum(1 for char in cleaned if char in vowels)
consonant_count = sum(1 for char in cleaned if [Link]() and char not
in vowels)
print("\n--- Text Analysis ---")
print(f"Total characters: {len(text)}")
print(f"Total words: {len(words)}")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")
string_operations_demo()
text_analyzer()
palindrome_checker()
Explanation: String manipulation is essential for text processing:
Indexing: text[0], text[-1]
Slicing: text[0:5] extracts characters 0-4
Methods: upper(), lower(), replace(), split()
String reversal: text[::-1]
2.2 Exercises: Programming
Exercise 1: Temperature Converter
Write a program that converts temperature between Celsius and Fahrenheit.
Formula: F = (C × 9/5) + 32 and C = (F - 32) × 5/9
Exercise 2: Prime Number Checker
Write a function that checks if a number is prime. A prime number is only divisible by 1 and
itself.
Exercise 3: Array Sum and Average
Write a program that takes 5 numbers as input, stores them in an array, and displays their
sum and average.
Exercise 4: File Word Counter
Write a program that opens a text file and counts the total number of words and lines in it.
Exercise 5: Pattern Printing
Write a program using nested loops to print the following pattern:
*
* *
* * *
* * * *
* * * * *
ANSWERS
Answer 1: Temperature Converter
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
choice = input("Enter 'C' for C->F or 'F' for F->C: ")
temp = float(input("Enter temperature: "))
if [Link]() == 'C':
result = celsius_to_fahrenheit(temp)
print(f"{temp}C = {result:.2f}F")
else:
result = fahrenheit_to_celsius(temp)
print(f"{temp}F = {result:.2f}C"
Answer 2: Prime Number Checker
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter number: "))
if is_prime(num):
print(f"{num} is prime")
else:
print(f"{num} is not prime")
Answer 3: Array Sum and Average
numbers = []
for i in range(5):
num = float(input(f"Enter number {i+1}: "))
[Link](num)
total = sum(numbers)
average = total / len(numbers)
print(f"Sum: {total}")
print(f"Average: {average:.2f}"
Answer 4: File Word Counter
filename = input("Enter filename: ")
with open(filename, 'r') as file:
content = [Link]()
lines = [Link]('\n')
words = [Link]()
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}"
Answer 5: Pattern Printing
for i in range(1, 6):
for j in range(1, i + 1):
print("* ", end="")
print()
PART 3: DATABASE SYSTEMS
3.1 Introduction to Databases
A database is an organized collection of structured data stored electronically. Database
Management Systems (DBMS) provide tools to create, maintain, and manipulate databases.
Key Concepts:
Data: Raw facts and information
Database: Organized collection of related data
DBMS: Software that manages databases
Schema: Logical structure of the database
Example 1: Creating Database Tables (SQL DDL)
-- Create the database
CREATE DATABASE SchoolDB;
USE SchoolDB;
-- Create STUDENTS table
CREATE TABLE Students (
StudentID VARCHAR(10) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
DateOfBirth DATE,
Gender CHAR(1),
Email VARCHAR(100) UNIQUE,
Phone VARCHAR(15),
Address VARCHAR(200),
EnrollmentDate DATE DEFAULT CURRENT_DATE
);
-- Create COURSES table
CREATE TABLE Courses (
CourseID VARCHAR(10) PRIMARY KEY,
CourseName VARCHAR(100) NOT NULL,
Description TEXT,
Credits INT DEFAULT 3,
Department VARCHAR(50),
Instructor VARCHAR(100)
);
-- Create ENROLLMENTS table (links Students and Courses)
CREATE TABLE Enrollments (
EnrollmentID INT AUTO_INCREMENT PRIMARY KEY,
StudentID VARCHAR(10) NOT NULL,
CourseID VARCHAR(10) NOT NULL,
Grade VARCHAR(2),
Semester VARCHAR(20),
Year INT,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
Explanation: SQL DDL commands define database structure:
CREATE TABLE: Creates a new table with specified columns and constraints
PRIMARY KEY: Uniquely identifies each record
FOREIGN KEY: Links table to another table's primary key
NOT NULL: Column must have a value
UNIQUE: No duplicate values allowed
Example 2: Inserting Data (SQL DML)
-- Insert single record into Students
INSERT INTO Students (StudentID, FirstName, LastName, DateOfBirth, Gender,
Email)
VALUES ('S2024001', 'John', 'Smith', '2006-05-15', 'M',
'[Link]@[Link]');
-- Insert multiple records at once
INSERT INTO Courses (CourseID, CourseName, Description, Credits, Department)
VALUES
('CS101', 'Introduction to Programming', 'Learn basic programming concepts', 3,
'Computer Science'),
('CS201', 'Data Structures', 'Arrays, linked lists, trees', 4, 'Computer
Science'),
('MATH101', 'Calculus I', 'Introduction to calculus', 4, 'Mathematics');
-- Insert enrollment records
INSERT INTO Enrollments (StudentID, CourseID, Grade, Semester, Year) VALUES
('S2024001', 'CS101', 'A', 'Fall', 2024),
('S2024001', 'MATH101', 'B+', 'Fall', 2024),
('S2024002', 'CS101', 'A-', 'Fall', 2024);
Explanation: INSERT adds new records to tables:
Single INSERT: Adds one row with specified values
Multiple INSERT: Adds multiple rows in one statement
Order of values must match column order (or column list order)
Example 3: Querying Data (SELECT)
-- Basic SELECT (retrieve all columns)
SELECT * FROM Students;
-- SELECT specific columns
SELECT StudentID, FirstName, LastName, Email FROM Students;
-- WHERE clause (filtering)
SELECT * FROM Students WHERE Gender = 'F';
SELECT * FROM Courses
WHERE Credits >= 3 AND Department = 'Computer Science';
-- LIKE pattern matching
SELECT * FROM Students WHERE LastName LIKE 'S%';
-- ORDER BY (sorting)
SELECT StudentID, Grade FROM Enrollments ORDER BY Grade DESC;
-- Aggregate functions
SELECT COUNT(*) AS TotalStudents FROM Students;
SELECT AVG(Credits) AS AvgCredits FROM Courses;
-- GROUP BY with aggregates
SELECT Department, COUNT(*) AS CourseCount, AVG(Credits) AS AvgCredits
FROM Courses GROUP BY Department;
-- HAVING (filter groups)
SELECT StudentID, COUNT(*) AS EnrolledCourses
FROM Enrollments GROUP BY StudentID HAVING COUNT(*) >= 2;
Explanation: SELECT retrieves data from databases:
* means all columns
WHERE filters rows before output
LIKE uses wildcards: % (any chars), _ (single char)
ORDER BY sorts results (ASC/DESC)
GROUP BY groups rows for aggregate functions
HAVING filters groups (like WHERE but for aggregates)
Example 4: Updating Data (UPDATE)
-- Update single column for single record
UPDATE Students
SET Email = '[Link]@[Link]'
WHERE StudentID = 'S2024001';
-- Update multiple columns
UPDATE Students
SET Address = '456 Oak Avenue',
Phone = '555-9876'
WHERE StudentID = 'S2024001';
-- Update with WHERE clause
UPDATE Courses
SET Credits = Credits + 1
WHERE Department = 'Computer Science';
-- Conditional update (case statement)
UPDATE Students
SET Status = CASE
WHEN EnrollmentDate < '2023-01-01' THEN 'Alumni'
WHEN EnrollmentDate < '2024-01-01' THEN 'Senior'
ELSE 'Regular'
END;
Explanation: UPDATE modifies existing records:
Always include WHERE clause to avoid updating all rows
Can update multiple columns in one statement
CASE statement allows conditional updates
Example 5: Deleting Data (DELETE)
-- Delete with WHERE clause
DELETE FROM Enrollments
WHERE StudentID = 'S2024001' AND CourseID = 'CS101';
-- Delete with subquery
DELETE FROM Students
WHERE StudentID NOT IN (
SELECT DISTINCT StudentID FROM Enrollments
);
-- DANGER: Never run these without proper backup!
-- DELETE FROM Students; -- All records gone!
-- DROP TABLE Students; -- Table structure + data gone!
-- Safe delete pattern (always backup first)
-- 1. SELECT * FROM table WHERE condition; -- Preview
-- 2. BEGIN TRANSACTION; -- Start transaction
-- 3. DELETE FROM table WHERE condition; -- Perform delete
-- 4. COMMIT; or ROLLBACK; -- Confirm or undo
Explanation: DELETE removes records from tables:
Always use WHERE clause to avoid deleting all records
DELETE removes rows, DROP removes entire table
Use transactions for safety
Example 6: Entity-Relationship Diagrams
Problem: Design an ERD for a library management system.
-- LIBRARY MANAGEMENT SYSTEM ERD Design
-- ===========================================
-- Entities and their attributes:
-- BOOK Entity
-- BookID (PK), Title, Author, ISBN, Publisher, YearPublished,
-- Category, CopiesAvailable, TotalCopies
-- MEMBER Entity
-- MemberID (PK), FirstName, LastName, Email, Phone,
-- Address, MembershipDate, MembershipType, FineBalance
-- LOAN Entity (Represents borrowing relationship)
-- LoanID (PK), BookID (FK), MemberID (FK),
-- DateBorrowed, DueDate, DateReturned, FineAmount
-- Relationships:
-- BOOK - LOAN: One-to-Many
-- MEMBER - LOAN: One-to-Many
CREATE TABLE Book (
BookID VARCHAR(10) PRIMARY KEY,
Title VARCHAR(200) NOT NULL,
Author VARCHAR(100) NOT NULL,
ISBN VARCHAR(20) UNIQUE,
CopiesAvailable INT DEFAULT 1
);
CREATE TABLE Member (
MemberID VARCHAR(10) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100),
FineBalance DECIMAL(10,2) DEFAULT 0
);
CREATE TABLE Loan (
LoanID INT AUTO_INCREMENT PRIMARY KEY,
BookID VARCHAR(10) NOT NULL,
MemberID VARCHAR(10) NOT NULL,
DateBorrowed DATE DEFAULT CURRENT_DATE,
DueDate DATE NOT NULL,
FOREIGN KEY (BookID) REFERENCES Book(BookID),
FOREIGN KEY (MemberID) REFERENCES Member(MemberID)
);
Explanation: ERD (Entity-Relationship Diagram) components:
Entity: Object with independent existence (Book, Member)
Attribute: Property of an entity (Title, Name)
Primary Key (PK): Unique identifier for each entity
Foreign Key (FK): Links to another entity's PK
Relationship: Association between entities (borrows)
Example 7: Database Normalization to 2NF
-- UNNORMALIZED TABLE (All data in one table)
-- StudentCourse table:
/*
StudentID | StudentName | Age | CourseID | CourseName | Instructor | Credits
S001 | John Smith | 17 | C001 | Programming| Dr. Brown | 4
S001 | John Smith | 17 | C002 | Database | Dr. Jones | 3
*/
-- Problems with unnormalized table:
-- 1. Data redundancy (StudentName repeated for same student)
-- 2. Update anomalies
-- 3. Insertion anomalies
-- 4. Deletion anomalies
-- SECOND NORMAL FORM (2NF):
-- Remove columns dependent only on part of composite key
CREATE TABLE Students (
StudentID VARCHAR(10) PRIMARY KEY,
StudentName VARCHAR(50) NOT NULL,
Age INT
);
CREATE TABLE Courses (
CourseID VARCHAR(10) PRIMARY KEY,
CourseName VARCHAR(50) NOT NULL,
Instructor VARCHAR(50),
Credits INT
);
CREATE TABLE Enrollments (
EnrollmentID INT PRIMARY KEY AUTO_INCREMENT,
StudentID VARCHAR(10),
CourseID VARCHAR(10),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID),
PRIMARY KEY (StudentID, CourseID) -- Composite key
);
Explanation: Normalization eliminates data redundancy:
1NF: Atomic values, no repeating groups
2NF: 1NF + No partial dependencies (no attribute depends on part of a composite key)
Benefits: No redundant data, easy updates, no anomalies
Example 8: SQL JOIN Operations
-- Sample data
INSERT INTO Students VALUES ('S001', 'John Smith', 17);
INSERT INTO Courses VALUES ('C001', 'Programming', 'Dr. Brown', 4);
INSERT INTO Enrollments (StudentID, CourseID) VALUES ('S001', 'C001');
-- INNER JOIN: Only matching records from both tables
SELECT [Link], [Link], [Link]
FROM Students S
INNER JOIN Enrollments E ON [Link] = [Link]
INNER JOIN Courses C ON [Link] = [Link];
-- LEFT JOIN: All from left table + matches from right
SELECT [Link], [Link]
FROM Students S
LEFT JOIN Enrollments E ON [Link] = [Link]
LEFT JOIN Courses C ON [Link] = [Link];
-- Result: Includes students even with no enrollment
-- FULL OUTER JOIN: All records from both tables
SELECT [Link], [Link]
FROM Students S
FULL OUTER JOIN Courses C ON [Link] = [Link];
Explanation: JOINs combine data from multiple tables:
INNER JOIN: Returns only matching rows
LEFT JOIN: Returns all rows from left table + matches
RIGHT JOIN: Returns all rows from right table + matches
FULL OUTER JOIN: Returns all rows from both tables
Example 9: Aggregate Functions and GROUP BY
-- COUNT: Number of records
SELECT COUNT(*) AS TotalStudents FROM Students;
SELECT COUNT(DISTINCT Department) AS NumDepartments FROM Courses;
-- SUM: Total of numeric values
SELECT SUM(Credits) AS TotalCreditsOffered FROM Courses;
-- AVG: Average of numeric values
SELECT AVG(Age) AS AverageStudentAge FROM Students;
-- MIN/MAX: Minimum and maximum values
SELECT MIN(Salary) AS LowestSalary, MAX(Salary) AS HighestSalary FROM Teachers;
-- GROUP BY: Group data before aggregation
SELECT Department, COUNT(*) AS CourseCount, AVG(Credits) AS AvgCredits
FROM Courses GROUP BY Department;
-- HAVING: Filter grouped results
SELECT StudentID, COUNT(*) AS NumCourses
FROM Enrollments GROUP BY StudentID
HAVING COUNT(*) >= 2;
Explanation: Aggregate functions perform calculations on sets of rows:
COUNT: Counts rows
SUM: Adds values
AVG: Calculates average
MIN/MAX: Finds extremes
GROUP BY: Groups rows before aggregation
HAVING: Filters groups (WHERE filters rows)
Example 10: Creating and Using Views
-- Create a view for easy student-course lookup
CREATE VIEW StudentCourseView AS
SELECT
[Link],
[Link],
[Link],
[Link]
FROM Students s
INNER JOIN Enrollments e ON [Link] = [Link]
INNER JOIN Courses c ON [Link] = [Link];
-- Use the view like a regular table
SELECT * FROM StudentCourseView WHERE StudentID = 'S001';
SELECT * FROM StudentCourseView WHERE CourseName = 'Programming';
-- Create a view for course enrollment counts
CREATE VIEW CourseEnrollmentStats AS
SELECT
[Link],
[Link],
COUNT([Link]) AS EnrolledStudents,
AVG([Link]) AS AverageGrade
FROM Courses c
LEFT JOIN Enrollments e ON [Link] = [Link]
GROUP BY [Link], [Link];
-- Benefits of views:
-- 1. Simplify complex queries
-- 2. Provide security layer (limit column access)
-- 3. Represent data differently than stored tables
Explanation: Views are virtual tables based on query results:
Store complex queries as reusable objects
Can restrict access to sensitive data
Don't store data - just stored queries
3.2 Exercises: Databases
Exercise 1: Table Design
Design a database for a hospital with patients, doctors, and appointments. Create the
necessary tables with appropriate primary keys and foreign keys.
Exercise 2: SQL Queries
Given a "Products" table with columns (ProductID, ProductName, Category, Price, Stock),
write SQL queries to:
List all products with price above $50
Find total stock value by category
Update price of all items in "Electronics" by 10%
Exercise 3: Normalization
Convert the following unnormalized table to 2NF:
Order(OrderID, OrderDate, CustomerName, CustomerAddress,
ProductID, ProductName, Quantity, UnitPrice)
Exercise 4: JOIN Query
Write a query to show all orders including customer name and product details using
appropriate JOINs.
Exercise 5: ERD Design
Draw an ERD for an online store with Customers, Products, Orders, and OrderItems entities.
Show the relationships between them.
ANSWERS
Answer 1: Hospital Database
CREATE TABLE Patients (
PatientID VARCHAR(10) PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DateOfBirth DATE,
Gender CHAR(1),
Phone VARCHAR(15)
);
CREATE TABLE Doctors (
DoctorID VARCHAR(10) PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Specialization VARCHAR(50)
);
CREATE TABLE Appointments (
AppointmentID INT PRIMARY KEY AUTO_INCREMENT,
PatientID VARCHAR(10),
DoctorID VARCHAR(10),
AppointmentDate DATE,
Reason VARCHAR(200),
FOREIGN KEY (PatientID) REFERENCES Patients(PatientID),
FOREIGN KEY (DoctorID) REFERENCES Doctors(DoctorID)
);
Answer 2: SQL Queries
-- All products above $50
SELECT * FROM Products WHERE Price > 50;
-- Total stock by category
SELECT Category, SUM(Stock * Price) AS TotalValue
FROM Products GROUP BY Category;
-- Update electronics prices by 10%
UPDATE Products SET Price = Price * 1.10
WHERE Category = 'Electronics';
Answer 3: Normalization to 2NF
Tables in 2NF:
Orders(OrderID PK, OrderDate, CustomerID FK)
Customers(CustomerID PK, CustomerName, CustomerAddress)
Products(ProductID PK, ProductName, UnitPrice)
OrderItems(OrderID FK, ProductID FK, Quantity, PRIMARY KEY(OrderID, ProductID))
Answer 4: JOIN Query
SELECT [Link], [Link], [Link],
[Link], [Link], [Link]
FROM Orders o
JOIN Customers c ON [Link] = [Link]
JOIN OrderItems oi ON [Link] = [Link]
JOIN Products p ON [Link] = [Link];
Answer 5: Online Store ERD
Relationships:
Customer - Order: One-to-Many (one customer has many orders)
Order - OrderItems: One-to-Many
Product - OrderItems: One-to-Many
OrderItems links Order and Product (Many-to-Many resolved)
PART 4: SAMPLE EXAMINATION PAPERS
EXAMINATION 1: ALGORITHMS
Time: 1 hour | Total Marks: 50
Question 1 (10 marks)
a) Draw a flowchart for an algorithm that reads 10 numbers and finds their average.
b) Write the equivalent pseudocode.
Question 2 (10 marks)
Trace the bubble sort algorithm for the following array: [42, 29, 15, 67, 23]
Question 3 (10 marks)
Compare linear search and binary search. Under what conditions is binary search
applicable?
Question 4 (10 marks)
Write pseudocode for a program that:
Accepts a student's test score
Awards a prize based on: Score ≥ 90: "Gold", ≥ 80: "Silver", ≥ 70: "Bronze", otherwise:
"No prize"
Question 5 (10 marks)
Using a trace table, show the execution of binary search for array [5, 12, 18, 25, 33, 42, 56]
to find target value 33.
EXAMINATION 2: PROGRAMMING
Time: 1 hour | Total Marks: 50
Question 1 (10 marks)
Write a Python program that:
Declares variables for a student's name, age, and three test scores
Calculates and displays the average score
Determines and displays the letter grade (A≥90, B≥80, C≥70, D≥60, F<60)
Question 2 (10 marks)
Write a Python function that uses a FOR loop to calculate the factorial of a number n.
Question 3 (10 marks)
Explain the difference between a WHILE loop and a FOR loop. Give an example of when each
would be used.
Question 4 (10 marks)
Write Python code to:
Create a list of 5 numbers
Find and display the maximum and minimum values
Sort the list in ascending order
Question 5 (10 marks)
Write a Python program using nested FOR loops to display the following pattern:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
EXAMINATION 3: DATABASES
Time: 1 hour | Total Marks: 50
Question 1 (10 marks)
a) Explain what a primary key is and why it is important in database design.
b) What is a foreign key? How does it establish relationships?
Question 2 (10 marks)
Write SQL statements to:
Create a table called "Employees" with columns: EmployeeID (PK), Name, Position,
Salary
Insert 3 sample records
Update the salary of an employee
Question 3 (10 marks)
Convert the following unnormalized table to Second Normal Form (2NF):
Sales(SalespersonID, SalespersonName, Region,
ProductID, ProductName, UnitsSold)
Question 4 (10 marks)
Write SQL queries to:
Select all employees earning above average salary
Count the number of employees in each position
Question 5 (10 marks)
Draw an ERD for a library system with Books, Members, and Loans. Show the relationships
and identify primary keys.
EXAMINATION 4: COMPREHENSIVE TEST
Time: 2 hours | Total Marks: 100
Section A: Algorithms (35 marks)
1. Explain the three basic structures in structured programming.
2. Write pseudocode for a program that checks if a number is prime.
3. Trace binary search for array [4, 8, 12, 16, 20, 24, 28] to find 16.
Section B: Programming (35 marks)
4. Write a Python function with parameters that calculates compound interest.
5. Explain the difference between global and local variables.
6. Write Python code to read 5 integers into a list and find the sum.
Section C: Databases (30 marks)
7. What is normalization? Why is it important?
8. Write SQL to create a foreign key relationship between two tables.
9. Explain the difference between DELETE and DROP commands.
EXAMINATION 5: FINAL EXAM PREPARATION
Time: 3 hours | Total Marks: 100
Part 1: Algorithms (40 marks)
Pseudocode and flowchart interpretation (15 marks)
Sorting algorithm analysis (10 marks)
Search algorithm comparison (10 marks)
Trace table construction (5 marks)
Part 2: Programming (30 marks)
Code analysis and debugging (10 marks)
Program design and implementation (10 marks)
Array manipulation (10 marks)
Part 3: Databases (30 marks)
ERD design and interpretation (10 marks)
SQL query writing (10 marks)
Normalization to 2NF (10 marks)