Form5 Computer Science Study Guide
Form5 Computer Science Study Guide
FORM 5
COMPREHENSIVE STUDY GUIDE
Section 1: Algorithms
1.6 Exercises
Section 2: Databases
2.7 Exercises
Section 3: Programming
3.6 Arrays
3.9 Exercises
// ===========================================
// EXAMPLE 1: Simple Input and Output
// ===========================================
BEGIN
// Declare a variable to store the user's name
DECLARE STRING userName
END
// EXPLANATION:
// - DECLARE creates a variable of a specific data type
// - OUTPUT displays text or values to the screen
// - INPUT accepts data from the user
// - STRING is a data type for storing text
// ===========================================
// EXAMPLE 2: Selection - IF-ELSE Statement
// ===========================================
BEGIN
DECLARE INTEGER marks
DECLARE STRING result
// EXPLANATION:
// - IF-ELSE is used for decision making
// - THEN block executes if condition is TRUE
// - ELSE block executes if condition is FALSE
// ===========================================
// EXAMPLE 3: Multiple Selection - ELSE-IF
// ===========================================
BEGIN
DECLARE INTEGER marks
END
// EXPLANATION:
// - ELSE IF allows multiple conditions to be checked
// - Conditions are evaluated top to bottom
// - First TRUE condition's block executes
Repetition structures (loops) allow a set of instructions to be executed multiple times. There are
three main types: FOR, WHILE, and REPEAT-UNTIL.
// ===========================================
// EXAMPLE 4: FOR Loop - Counted Repetition
// ===========================================
BEGIN
DECLARE INTEGER counter
FOR counter = 1 TO 10
OUTPUT counter
END FOR
// EXPLANATION:
// - FOR loop repeats a specific number of times
// - counter starts at 1, increments by 1 each iteration
// - Loop ends when counter exceeds 10
Objective: Write pseudocode to find the sum of positive numbers until user enters 0.
// ===========================================
// EXAMPLE 5: WHILE Loop - Condition-Controlled
// ===========================================
BEGIN
DECLARE INTEGER number
DECLARE INTEGER sum
sum = 0
// EXPLANATION:
// - WHILE loop repeats as long as condition is TRUE
// - Condition is checked BEFORE each iteration
Objective: Write pseudocode to sort an array of numbers in ascending order using Bubble Sort.
// ===========================================
// EXAMPLE 6: Bubble Sort Algorithm
// ===========================================
BEGIN
DECLARE INTEGER numbers[5]
DECLARE INTEGER i, j, temp, n
n = 5
END
// EXPLANATION:
// - Bubble Sort compares adjacent elements
// - Swaps if out of order
// - Time complexity: O(n²)
1.5 Standard Algorithms: Searching
// ===========================================
// EXAMPLE 7: Linear Search Algorithm
// ===========================================
BEGIN
DECLARE INTEGER numbers[8]
DECLARE INTEGER searchKey, position, i
DECLARE BOOLEAN found
found = FALSE
position = -1
FOR i = 0 TO 7
IF numbers[i] = searchKey THEN
position = i
found = TRUE
OUTPUT "Found at position " + (i + 1)
BREAK
END IF
END FOR
END
// EXPLANATION:
// - Linear Search checks each element sequentially
// - Time complexity: O(n)
Objective: Write pseudocode to find a number in a sorted array using Binary Search.
// ===========================================
// EXAMPLE 8: Binary Search Algorithm
// ===========================================
BEGIN
DECLARE INTEGER arr[10]
DECLARE INTEGER first, last, middle, searchKey
DECLARE BOOLEAN found
first = 0
last = 9
found = FALSE
END
// EXPLANATION:
// - Binary Search requires a SORTED array
// - Divides search interval in half each iteration
// - Time complexity: O(log n)
1.6 Exercises
• EXERCISE 1: Write pseudocode to accept three numbers and display the largest one. Use IF-
ELSE statements.
• EXERCISE 2: Write pseudocode to calculate the factorial of a number using a WHILE loop. (Hint:
5! = 5 × 4 × 3 × 2 × 1 = 120)
• EXERCISE 3: Write pseudocode to check if a number is prime. A prime number is only divisible
by 1 and itself.
• EXERCISE 4: Write pseudocode to reverse a given string. For example, "HELLO" becomes
"OLLEH".
• EXERCISE 5: Modify the Bubble Sort algorithm to sort in descending order (largest to smallest).
QUESTION 1: (a) Define an algorithm. (b) List two characteristics of a good algorithm. (c) Write
pseudocode to check if a year is a leap year.
QUESTION 2: (a) Explain the difference between FOR and WHILE loops. (b) Write pseudocode
using a nested FOR loop to display a pattern of stars.
QUESTION 3: (a) Describe the Bubble Sort algorithm. (b) Trace through the following array using
Bubble Sort: [5, 2, 8, 1, 9]
QUESTION 4: (a) Explain why Binary Search is more efficient than Linear Search. (b) Write
pseudocode for Binary Search. (c) State two requirements for Binary Search.
QUESTION 5: Write pseudocode for a program that: (a) Accepts 10 student names and marks, (b)
Calculates the average mark, (c) Displays names of students who scored above average.
SECTION 2: DATABASE SYSTEMS
using System;
using [Link];
namespace FileBasedDatabase
{
class Program
{
// ===========================================
// EXAMPLE 1: File-Based Database System
// ===========================================
switch(choice)
{
case "1":
AddStudent(filePath);
break;
case "2":
ViewAllStudents(filePath);
break;
case "3":
SearchStudent(filePath);
break;
}
}
static void AddStudent(string filePath)
{
[Link]("Enter Student ID: ");
string id = [Link]();
[Link]("Enter Name: ");
string name = [Link]();
[Link]("Enter Grade: ");
string grade = [Link]();
if () return;
-- ===========================================
-- EXAMPLE 2: SQL DATABASE OPERATIONS
-- ===========================================
-- EXPLANATION:
// - CREATE DATABASE creates a new database
// - CREATE TABLE defines table structure
// - PRIMARY KEY uniquely identifies each record
// - INSERT adds new records
// - SELECT retrieves data
// - UPDATE modifies existing records
// - DELETE removes records
-- ===========================================
-- EXAMPLE 3: DDL COMMANDS WITH CONSTRAINTS
-- ===========================================
-- CONSTRAINT EXPLANATION:
// PRIMARY KEY: Uniquely identifies each row
// NOT NULL: Column must have a value
// UNIQUE: All values must be different
// CHECK: Validates values meet a condition
// DEFAULT: Provides default value
// FOREIGN KEY: Links to another table's PK
Objective: Show complete CRUD (Create, Read, Update, Delete) operations using C#.
using System;
using [Link];
namespace DatabaseCRUD
{
class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Grade { get; set; }
}
class DatabaseManager
{
private static List<Student> students = new List<Student>();
// ===========================================
// EXAMPLE 4: CRUD OPERATIONS DEMO
// ===========================================
// EXPLANATION:
// - CRUD = Create, Read, Update, Delete
// - CREATE: Uses Add() method to add new records
// - READ: Uses Find() and foreach loop to retrieve data
// - UPDATE: Modifies existing object's properties
// - DELETE: Uses Remove() to delete records
-- ===========================================
-- EXAMPLE 5: RELATIONAL DATABASE DESIGN
-- ===========================================
-- EXPLANATION:
// - ERD shows entities (tables) and relationships
// - 1:M relationship uses FOREIGN KEY on many side
// - Loan table connects Book and Member
-- ===========================================
-- EXAMPLE 6: SQL JOINS AND SUBQUERIES
-- ===========================================
-- EXPLANATION:
// - INNER JOIN: Only matching records
// - LEFT JOIN: All rows from left table
// - Subquery: Inner query provides values for outer
2.8 Exercises
• EXERCISE 1: Create a table called 'Products' with fields: ProductID (PK), ProductName, Price,
StockQuantity. Add appropriate constraints.
• EXERCISE 2: Write SQL to insert 5 product records into the Products table.
• EXERCISE 3: Write a query to find all products with stock quantity less than 10, sorted by
product name.
• EXERCISE 4: Create a database design for a simple bank system with Customers and Accounts
tables. Show the relationship between them.
• EXERCISE 5: Write a C# program that demonstrates the difference between file-based storage
and database storage.
QUESTION 1: (a) Define a database and DBMS. (b) List three advantages of using a DBMS over
file-based systems. (c) Draw an ERD for a school exam system.
QUESTION 2: (a) Explain the following SQL commands: SELECT, INSERT, UPDATE, DELETE. (b)
Write SQL to create a 'Teachers' table with at least 5 fields.
QUESTION 3: (a) What is a primary key? (b) What is a foreign key? (c) Why are they important in
relational databases?
QUESTION 4: (a) Explain the difference between DDL and DML. (b) Give two examples of each.
(c) Write the SQL to add a new column 'Email' to the Students table.
QUESTION 5: (a) What is normalization? (b) Explain 1NF, 2NF, and 3NF with examples.
SECTION 3: PROGRAMMING
Programming is the process of creating instructions that a computer can execute. Using C# Console
Application, we will learn fundamental programming concepts that apply to all languages.
using System;
namespace DataTypesDemo
{
class Program
{
// ===========================================
// EXAMPLE 1: VARIABLES AND DATA TYPES
// ===========================================
// TEXT TYPES
string studentName = "John Smith"; // Text (double quotes)
char grade = 'A'; // Single character
// BOOLEAN TYPE
bool isPassed = true; // True or false
// DISPLAYING VARIABLES
[Link]($"Name: {studentName}");
[Link]($"Age: {age}");
[Link]($"Grade: {grade}");
// EXPLANATION:
// - Variables are containers for storing data values
// - int: Whole numbers
// - double: Decimal numbers
// - decimal: For money calculations
// - string: Text (collection of characters)
// - char: Single character
// - bool: True or false values
using System;
namespace InputOutputDemo
{
class Program
{
// ===========================================
// EXAMPLE 2: INPUT AND OUTPUT OPERATIONS
// ===========================================
// FORMATTED OUTPUT
string name = "Alice";
int age = 15;
double gpa = 3.75;
[Link]($"\nName: {userName}");
[Link]($"Next year you will be {userAge + 1}");
// CLEAR SCREEN
[Link]();
// COLORED OUTPUT
[Link] = [Link];
[Link]("SUCCESS: Operation completed!");
[Link]();
}
}
}
// EXPLANATION:
// - [Link]() outputs text with new line
// - [Link]() outputs text without new line
// - [Link]() waits for user input
// - $ string literal embeds variables directly
using System;
namespace ConditionalDemo
{
class Program
{
// ===========================================
// EXAMPLE 3: CONDITIONAL STATEMENTS
// ===========================================
// Single condition
if (score >= 90)
{
[Link]("Grade: A (Excellent!)");
}
else if (score >= 80)
{
[Link]("Grade: B (Good job!)");
}
else if (score >= 70)
{
[Link]("Grade: C (Satisfactory)");
}
else
{
[Link]("Grade: F (Failed)");
}
// LOGICAL OPERATORS
[Link]("\nEnter your age: ");
int age = [Link]([Link]());
[Link]("Do you have a license? (true/false): ");
bool hasLicense = [Link]([Link]());
// SWITCH STATEMENT
[Link]("\nEnter day number (1-7): ");
int day = [Link]([Link]());
switch (day)
{
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Saturday"); break;
case 7: [Link]("Sunday"); break;
default: [Link]("Invalid day!"); break;
}
}
}
}
// EXPLANATION:
// - IF checks condition; if TRUE, executes block
// - ELSE IF checks next condition if previous was FALSE
// - && (AND): Both conditions must be TRUE
// - SWITCH: Tests one variable against multiple values
using System;
namespace LoopsDemo
{
class Program
{
// ===========================================
// EXAMPLE 4: LOOPS AND ITERATION
// ===========================================
static void Main(string[] args)
{
// FOR LOOP (counted repetition)
[Link]("=== FOR LOOP ===");
for (int i = 1; i <= 5; i++)
{
[Link](i + " ");
}
[Link]("Access granted!");
// EXPLANATION:
// - FOR: Use when you know exact iteration count
// - FOR-EACH: Iterate through arrays/collections
// - WHILE: Use when iteration count is unknown
// - DO-WHILE: Executes at least once
// - BREAK: Exits loop immediately
// - CONTINUE: Skips to next iteration
3.6 Arrays
using System;
namespace ArraysDemo
{
class Program
{
// ===========================================
// EXAMPLE 5: ARRAYS IN C#
// ===========================================
// Access elements
[Link]("First: " + numbers[0]); // 10
[Link]("Last: " + numbers[4]); // 50
[Link]("Length: " + [Link]);
// Find element
int search = 30;
int index = [Link](numbers, search);
[Link]($"\nIndex of {search}: {index}");
// Sort array
int[] unsorted = { 5, 2, 8, 1, 9 };
[Link](unsorted);
[Link]($"Sorted: {[Link](", ", unsorted)}");
// Two-dimensional array
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
[Link]($"\nMatrix[1,2]: {matrix[1, 2]}"); // 6
}
}
}
// EXPLANATION:
// - Arrays store multiple values of the same type
// - Index starts at 0 (first element is index 0)
// - Length property returns number of elements
// - 2D arrays are like tables with rows and columns
Example 6: Methods in C#
using System;
namespace MethodsDemo
{
class Program
{
// ===========================================
// EXAMPLE 6: FUNCTIONS AND PROCEDURES
// ===========================================
// EXPLANATION:
// - METHODS are reusable blocks of code
// - PROCEDURE: Performs action, no return (void)
// - FUNCTION: Returns a value (specify return type)
// - Parameters are input values passed to method
using System;
using [Link];
namespace FileHandlingDemo
{
class Program
{
// ===========================================
// EXAMPLE 7: FILE HANDLING OPERATIONS
// ===========================================
// WRITE TO FILE
[Link]("Enter text to save: ");
string text = [Link]();
[Link](filePath, text);
[Link]("Data saved!");
// APPEND TO FILE
string[] lines = { "Line 1", "Line 2", "Line 3" };
using (StreamWriter sw = [Link](filePath))
{
foreach (string line in lines)
{
[Link](line);
}
}
[Link]("Lines appended!");
// FILE INFORMATION
[Link]($"File exists: {[Link](filePath)}");
[Link]($"Size: {new FileInfo(filePath).Length}
bytes");
[Link]($"Modified:
{[Link](filePath)}");
}
}
}
// EXPLANATION:
// - [Link]() writes and overwrites
// - [Link]() reads entire file
// - [Link]() adds to end of file
// - [Link]() checks if file exists
// - using statement ensures proper cleanup
3.9 Exercises
• EXERCISE 1: Write a C# program that accepts three numbers and displays the largest one using
IF-ELSE statements.
• EXERCISE 2: Create a program that generates the Fibonacci sequence up to 10 terms using a
WHILE loop. (Hint: 0, 1, 1, 2, 3, 5, 8, ...)
• EXERCISE 3: Write a program that stores 5 student names in an array and displays them in
reverse order.
• EXERCISE 4: Create a function that accepts a string and returns the number of vowels (a, e, i, o,
u) in it.
• EXERCISE 5: Write a program that reads data from a file, displays it, and then writes user input
to a new file.
QUESTION 1: (a) Define a variable and a constant. (b) List three data types in C# and their uses.
(c) Write a program to swap two numbers without using a temporary variable.
QUESTION 2: (a) Explain the difference between WHILE and DO-WHILE loops. (b) Write a
program to print all even numbers from 1 to 100 using a FOR loop.
QUESTION 3: (a) What is an array? (b) Write a program to find the sum and average of 10
numbers stored in an array.
QUESTION 4: (a) Define a function and a procedure. (b) Write a function that calculates the
factorial of a number recursively.
QUESTION 5: (a) Explain the difference between passing by value and passing by reference. (b)
Write a program that demonstrates both methods.
SECTION 4: SAMPLE EXAMINATION PAPERS
The following examination papers cover all topics: Algorithms, Databases, and Programming. Each
paper is designed to test understanding, application, and problem-solving skills.
EXAMINATION PAPER 1
QUESTION 1: ALGORITHMS (25 marks)(a) (i) Define the term 'algorithm'. [2 marks]
(ii) List three characteristics of a good algorithm. [3 marks]
(b) Write pseudocode to find the sum of all even numbers from 1 to 100. [8 marks]
(c) Trace the Bubble Sort algorithm on the following array: [5, 3, 8, 1, 2] showing each pass. [12
marks]
QUESTION 2: DATABASE SYSTEMS (25 marks)(a) (i) What is the difference between a file-based
system and a DBMS? [4 marks]
(ii) List three advantages of using a relational database. [3 marks]
(c) Draw an Entity Relationship Diagram for a library system with Members, Books, and Loans. [6
marks]
QUESTION 3: PROGRAMMING (25 marks)(a) (i) What is the difference between a WHILE loop
and a FOR loop? [4 marks]
(ii) When would you use a DO-WHILE loop? [2 marks]
(c) Write a function that accepts two integers and returns their greatest common divisor (GCD). [9
marks]
EXAMINATION PAPER 2
QUESTION 1: PSEUDOCODE AND ALGORITHMS (25 marks)(a) (i) What is meant by 'selection' in
algorithm design? [2 marks]
(ii) Write pseudocode using nested IF statements to determine exam results. [5 marks]
(b) Write pseudocode for a program that accepts 10 numbers and displays the highest and lowest
values. [8 marks]
(c) Explain Linear Search and Binary Search. Under what conditions can Binary Search be used? [10
marks]
QUESTION 2: DATABASE DESIGN (25 marks)(a) (i) Define: Primary Key, Foreign Key, Candidate
Key. [6 marks]
(ii) What is normalization? Why is it important? [4 marks]
(c) Normalize the table: Student(StudentID, Name, Subject1, Subject2, Subject3) to 3NF. [5 marks]
QUESTION 3: PROGRAMMING FUNDAMENTALS (25 marks) (a) (i) What is a data type? List four
primitive data types in C#. [4 marks]
(ii) What is the difference between 'int' and 'double'? [2 marks]
EXAMINATION PAPER 3
(c) Trace Selection Sort on [64, 25, 12, 22, 11]. [11 marks]
QUESTION 2: SQL AND DATABASES (25 marks)(a) (i) What is DDL? List three DDL commands. [5
marks]
(ii) What is DML? List three DML commands. [5 marks]
(b) Consider tables Employees(EmpID, Name, DeptID, Salary) and Departments(DeptID, DeptName).
Write queries: [10 marks]
(i) List employees with department names
(ii) Total salary by department
(iii) Update salary by 10%
(iv) Delete employees from specific department
QUESTION 3: PROGRAMMING (25 marks)(a) (i) What is the purpose of comments? [2 marks]
(ii) Write code demonstrating good commenting. [5 marks]
(c) Explain passing by value vs passing by reference with code examples. [8 marks]
EXAMINATION PAPER 4
QUESTION 1: ALGORITHM DESIGN (25 marks)(a) (i) Draw a flowchart for checking positive,
negative, or zero. [5 marks]
(ii) Convert to pseudocode. [5 marks]
QUESTION 2: DATABASE SYSTEMS (25 marks)(a) (i) What is a relational database? [3 marks]
(ii) List three types of relationships. [6 marks]
QUESTION 3: C# PROGRAMMING (25 marks)(a) (i) Difference between Write() and WriteLine()?
[2 marks]
(ii) Difference between 'string' and 'char'? [2 marks]
(b) Write a C# program with: [12 marks]
(i) IsPrime method returning bool
(ii) Accept number and display if prime
(iii) Find all primes between 1-50
EXAMINATION PAPER 5
QUESTION 1: ALGORITHMS AND PROBLEM SOLVING (25 marks) (a) (i) Define pseudocode. [2
marks]
(ii) List three advantages of writing pseudocode. [3 marks]
(c) Trace table for pseudocode where n=5: total=0; FOR i=1 TO n; total=total+i; END FOR; OUTPUT
total [8 marks]
QUESTION 2: DATABASE DESIGN AND SQL (25 marks) (a) (i) Purpose of PRIMARY KEY? [3
marks]
(ii) Can a table have multiple foreign keys? Explain. [4 marks]
END OF DOCUMENT