0% found this document useful (0 votes)
1 views34 pages

Form5 Computer Science Study Guide

Uploaded by

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

Form5 Computer Science Study Guide

Uploaded by

ethantanakah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

COMPUTER SCIENCE

FORM 5
COMPREHENSIVE STUDY GUIDE

Algorithms, Databases, and Programming

Console Application with C#

10+ Step-by-Step Examples with Comments

5 Exercises + 5 Exam Questions Per Topic

Based on ZIMSEC Syllabus 2015-2022

Beginner-Friendly Guide with Detailed Explanations


Table of Contents
Introduction

Section 1: Algorithms

1.1 Pseudocode Basics

1.2 Selection Structures

1.3 Repetition/Iteration Structures

1.4 Standard Algorithms - Sorting

1.5 Standard Algorithms - Searching

1.6 Exercises

1.7 Exam Questions

Section 2: Databases

2.1 File-Based Database Systems

2.2 Database Management Systems (DBMS)

2.3 Relational Database Modeling

2.4 SQL Commands

2.5 Data Definition Language (DDL)

2.6 Data Manipulation Language (DML)

2.7 Exercises

2.8 Exam Questions

Section 3: Programming

3.1 Structured Programming Basics

3.2 Variables and Data Types

3.3 Input and Output

3.4 Conditional Statements


3.5 Loops and Iteration

3.6 Arrays

3.7 Functions and Procedures

3.8 File Handling

3.9 Exercises

3.10 Exam Questions

Section 4: Sample Examination Papers


SECTION 1: ALGORITHMS

1.1 Introduction to Algorithms

An algorithm is a step-by-step procedure for solving a problem or accomplishing a task. In computer


science, algorithms are expressed using pseudocode or flowcharts before implementation in a
programming language.

1.2 Pseudocode Basics

Pseudocode is a simplified, structured way to express algorithms using a combination of natural


language and programming constructs. It is not tied to any specific programming language.

Example 1: Simple Input and Output

Objective: Write pseudocode to accept a user's name and display a greeting.

// ===========================================
// EXAMPLE 1: Simple Input and Output
// ===========================================

BEGIN
// Declare a variable to store the user's name
DECLARE STRING userName

// Prompt the user to enter their name


OUTPUT "Enter your name: "

// Accept input from the user


INPUT userName

// Display a personalized greeting


OUTPUT "Hello, " + userName + "! Welcome!"

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)

Objective: Write pseudocode to check if a student passed an exam.

// ===========================================
// EXAMPLE 2: Selection - IF-ELSE Statement
// ===========================================
BEGIN
DECLARE INTEGER marks
DECLARE STRING result

OUTPUT "Enter the student's marks (0-100): "


INPUT marks

// Check if the student passed (pass mark is 50)


IF marks >= 50 THEN
result = "PASS"
OUTPUT "Congratulations! You passed."
ELSE
result = "FAIL"
OUTPUT "Unfortunately, you failed."
END IF

OUTPUT "Final Result: " + result


END

// 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)

Objective: Write pseudocode to determine a grade based on marks.

// ===========================================
// EXAMPLE 3: Multiple Selection - ELSE-IF
// ===========================================

BEGIN
DECLARE INTEGER marks

OUTPUT "Enter the student's marks (0-100): "


INPUT marks

IF marks >= 75 THEN


OUTPUT "Grade: A (Distinction)"
ELSE IF marks >= 60 THEN
OUTPUT "Grade: B (Credit)"
ELSE IF marks >= 50 THEN
OUTPUT "Grade: C (Pass)"
ELSE
OUTPUT "Grade: F (Fail)"
END IF

END

// EXPLANATION:
// - ELSE IF allows multiple conditions to be checked
// - Conditions are evaluated top to bottom
// - First TRUE condition's block executes

1.3 Repetition Structures

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

Objective: Write pseudocode to display numbers from 1 to 10.

// ===========================================
// EXAMPLE 4: FOR Loop - Counted Repetition
// ===========================================

BEGIN
DECLARE INTEGER counter

FOR counter = 1 TO 10
OUTPUT counter
END FOR

OUTPUT "Counting complete!"


END

// EXPLANATION:
// - FOR loop repeats a specific number of times
// - counter starts at 1, increments by 1 each iteration
// - Loop ends when counter exceeds 10

Example 5: WHILE Loop

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

OUTPUT "Enter positive numbers (enter 0 to stop): "


INPUT number

WHILE number <> 0


sum = sum + number
OUTPUT "Current sum: " + sum
INPUT number
END WHILE
OUTPUT "The total sum is: " + sum
END

// EXPLANATION:
// - WHILE loop repeats as long as condition is TRUE
// - Condition is checked BEFORE each iteration

1.4 Standard Algorithms: Sorting

Example 6: Bubble Sort Algorithm

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

OUTPUT "Enter 5 numbers:"


FOR i = 0 TO 4
INPUT numbers[i]
END FOR

// Bubble Sort - compare adjacent elements


FOR i = 0 TO n - 2
FOR j = 0 TO n - 2 - i
IF numbers[j] > numbers[j + 1] THEN
temp = numbers[j]
numbers[j] = numbers[j + 1]
numbers[j + 1] = temp
END IF
END FOR
END FOR

OUTPUT "Sorted array (ascending):"


FOR i = 0 TO 4
OUTPUT numbers[i]
END FOR

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

Objective: Write pseudocode to find a number in an array using Linear Search.

// ===========================================
// EXAMPLE 7: Linear Search Algorithm
// ===========================================

BEGIN
DECLARE INTEGER numbers[8]
DECLARE INTEGER searchKey, position, i
DECLARE BOOLEAN found

found = FALSE
position = -1

OUTPUT "Enter 8 numbers:"


FOR i = 0 TO 7
INPUT numbers[i]
END FOR

OUTPUT "Enter the number to search for:"


INPUT searchKey

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

IF found = FALSE THEN


OUTPUT "Element not found."
END IF

END

// EXPLANATION:
// - Linear Search checks each element sequentially
// - Time complexity: O(n)

Example 8: Binary Search Algorithm

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

OUTPUT "Enter 10 numbers in ASCENDING order:"


FOR i = 0 TO 9
INPUT arr[i]
END FOR

OUTPUT "Enter number to search:"


INPUT searchKey

WHILE first <= last AND found = FALSE


middle = (first + last) / 2

IF arr[middle] = searchKey THEN


found = TRUE
OUTPUT "Found at position " + (middle + 1)
ELSE IF arr[middle] < searchKey THEN
first = middle + 1
ELSE
last = middle - 1
END IF
END WHILE

IF found = FALSE THEN


OUTPUT "Element not found."
END IF

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

1.7 Exam Questions

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

2.1 Introduction to Database Systems

A database is an organized collection of structured data stored electronically. Database


Management Systems (DBMS) are software applications used to create, manage, and manipulate
databases.

2.2 File-Based vs DBMS Approach

Example 1: File-Based System (C# Implementation)

Objective: Demonstrate how data is stored in a file-based system using C#.

using System;
using [Link];

namespace FileBasedDatabase
{
class Program
{
// ===========================================
// EXAMPLE 1: File-Based Database System
// ===========================================

static void Main(string[] args)


{
string filePath = "[Link]";

[Link]("=== FILE-BASED DATABASE DEMO ===");


[Link]("1. Add Student");
[Link]("2. View All Students");
[Link]("3. Search Student");
[Link]("Enter choice: ");

string choice = [Link]();

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]();

string record = $"{id}|{name}|{grade}";

using (StreamWriter sw = [Link](filePath))


{
[Link](record);
}
[Link]("Student added successfully!");
}

static void ViewAllStudents(string filePath)


{
if (![Link](filePath))
{
[Link]("No records found.");
return;
}

string[] lines = [Link](filePath);

[Link]("\n=== STUDENT RECORDS ===");


foreach (string line in lines)
{
string[] parts = [Link]('|');
[Link]($"{parts[0]} | {parts[1]} | {parts[2]}");
}
}

static void SearchStudent(string filePath)


{
[Link]("Enter Student ID to search: ");
string searchId = [Link]();

if (![Link](filePath)) return;

string[] lines = [Link](filePath);


foreach (string line in lines)
{
string[] parts = [Link]('|');
if (parts[0] == searchId)
{
[Link]($"Found: {parts[0]} | {parts[1]} |
{parts[2]}");
return;
}
}
[Link]("Student not found.");
}
}
}
// EXPLANATION:
// - File-based systems store data in text files
// - Pipe (|) character separates fields
// - Limitation: No built-in search, sorting, or security

2.3 SQL Database Operations

Example 2: SQL Database Operations

Objective: Show how SQL is used to create and manipulate databases.

-- ===========================================
-- EXAMPLE 2: SQL DATABASE OPERATIONS
-- ===========================================

-- Create a new database


CREATE DATABASE SchoolDB;
USE SchoolDB;

-- Create Students table


CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
DateOfBirth DATE,
Grade CHAR(1)
);

-- Create Courses table


CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100) NOT NULL,
Teacher VARCHAR(50)
);

-- Insert student records


INSERT INTO Students (StudentID, FirstName, LastName, DateOfBirth, Grade)
VALUES (1, 'John', 'Smith', '2005-03-15', 'A');

INSERT INTO Students (StudentID, FirstName, LastName, DateOfBirth, Grade)


VALUES (2, 'Mary', 'Johnson', '2004-07-22', 'B');

-- Select all students


SELECT * FROM Students;

-- Select specific columns


SELECT FirstName, LastName, Grade FROM Students;

-- Filter with WHERE


SELECT * FROM Students WHERE Grade = 'A';

-- Update a student's grade


UPDATE Students SET Grade = 'A+' WHERE StudentID = 2;
-- Delete a student
DELETE FROM Students WHERE StudentID = 3;

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

2.4 Data Definition Language (DDL)

Example 3: DDL Commands with Constraints

Objective: Demonstrate how to create tables with various constraints.

-- ===========================================
-- EXAMPLE 3: DDL COMMANDS WITH CONSTRAINTS
-- ===========================================

-- Create Employee table with multiple constraints


CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
Salary DECIMAL(10, 2) CHECK (Salary > 0),
DepartmentID INT,
HireDate DATE DEFAULT CURRENT_DATE,
Age INT CHECK (Age >= 18 AND Age <= 65),
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);

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

-- Modify existing table


ALTER TABLE Employees ADD PhoneNumber VARCHAR(20);
ALTER TABLE Employees DROP COLUMN PhoneNumber;
DROP TABLE Employees;
2.5 Data Manipulation Language (DML)

Example 4: CRUD Operations in C#

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
// ===========================================

static void Main(string[] args)


{
// Initialize with sample data
[Link](new Student { StudentID = 1, Name = "John Smith",
Age = 15, Grade = "A" });
[Link](new Student { StudentID = 2, Name = "Mary Johnson",
Age = 16, Grade = "B" });

// CREATE - Add new record


Student newStudent = new Student {
StudentID = 3,
Name = "Sarah Wilson",
Age = 16,
Grade = "A"
};
[Link](newStudent);
[Link]($"INSERT: Added {[Link]}");

// READ - Get all students


[Link]("\n=== ALL STUDENTS ===");
foreach (var s in students)
{
[Link]($"{[Link]} | {[Link]} | {[Link]} |
{[Link]}");
}

// UPDATE - Modify student's grade


var student = [Link](s => [Link] == 2);
if (student != null)
{
[Link] = "B+";
[Link]($"\nUPDATE: {[Link]}'s grade changed
to B+");
}

// DELETE - Remove student


var toDelete = [Link](s => [Link] == 3);
if (toDelete != null)
{
[Link](toDelete);
[Link]($"DELETE: Removed {[Link]}");
}
}
}
}

// 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

2.6 Relational Database Modeling

Example 5: Entity Relationship Diagram (ERD)

Objective: Show how to model a library database using ERD concepts.

-- ===========================================
-- EXAMPLE 5: RELATIONAL DATABASE DESIGN
-- ===========================================

-- Entities: Book, Member, Loan


-- Relationships: Member borrows Book (1:M)

CREATE TABLE Members (


MemberID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100),
Phone VARCHAR(20),
JoinDate DATE DEFAULT CURRENT_DATE
);

CREATE TABLE Books (


BookID INT PRIMARY KEY,
Title VARCHAR(200) NOT NULL,
Author VARCHAR(100),
ISBN VARCHAR(20) UNIQUE,
Available BOOLEAN DEFAULT TRUE
);

CREATE TABLE Loans (


LoanID INT PRIMARY KEY,
MemberID INT,
BookID INT,
LoanDate DATE,
DueDate DATE,
ReturnDate DATE NULL,
FOREIGN KEY (MemberID) REFERENCES Members(MemberID),
FOREIGN KEY (BookID) REFERENCES Books(BookID)
);

-- Find all books on loan


SELECT [Link], [Link], [Link], [Link]
FROM Books b
JOIN Loans l ON [Link] = [Link]
JOIN Members m ON [Link] = [Link]
WHERE [Link] IS NULL;

-- EXPLANATION:
// - ERD shows entities (tables) and relationships
// - 1:M relationship uses FOREIGN KEY on many side
// - Loan table connects Book and Member

2.7 SQL Joins and Subqueries

Example 6: Joins and Subqueries

-- ===========================================
-- EXAMPLE 6: SQL JOINS AND SUBQUERIES
-- ===========================================

-- Create sample tables


CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50)
);

CREATE TABLE Employees (


EmpID INT PRIMARY KEY,
Name VARCHAR(100),
DeptID INT REFERENCES Departments(DeptID),
Position VARCHAR(50)
);

-- INNER JOIN: Returns matching records


SELECT [Link], [Link], [Link]
FROM Employees e
INNER JOIN Departments d ON [Link] = [Link];

-- LEFT JOIN: All from left + matching from right


SELECT [Link], [Link]
FROM Employees e
LEFT JOIN Departments d ON [Link] = [Link];

-- SUBQUERY: Query within a query


-- Find employees earning above average
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);

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

2.9 Exam Questions

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

3.1 Introduction to 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.

3.2 Variables and Data Types

Example 1: Variables and Data Types

Objective: Demonstrate different data types and how to declare variables.

using System;

namespace DataTypesDemo
{
class Program
{
// ===========================================
// EXAMPLE 1: VARIABLES AND DATA TYPES
// ===========================================

static void Main(string[] args)


{
// INTEGER TYPES (whole numbers)
int age = 16; // 32-bit signed integer
long population = 15000000L; // 64-bit signed integer
short score = 95; // 16-bit signed integer
byte level = 5; // 8-bit unsigned (0-255)

// DECIMAL TYPES (floating-point numbers)


double temperature = 36.5; // 64-bit floating point
float height = 5.8f; // 32-bit floating point
decimal price = 99.99m; // High precision (for money)

// 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}");

// TYPE CONVERSION (Casting)


double pi = 3.14159;
int intPi = (int)pi; // Converts to 3
[Link]($"Pi as integer: {intPi}");

// PARSING STRINGS TO NUMBERS


string numStr = "42";
int convertedNum = [Link](numStr);
[Link]($"Parsed number: {convertedNum}");

// Getting user input


[Link]("\nEnter your favorite number: ");
int favNum = [Link]([Link]());
[Link]($"Doubled: {favNum * 2}");
}
}
}

// 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

3.3 Input and Output

Example 2: User Input and Output Operations

using System;

namespace InputOutputDemo
{
class Program
{
// ===========================================
// EXAMPLE 2: INPUT AND OUTPUT OPERATIONS
// ===========================================

static void Main(string[] args)


{
// SIMPLE OUTPUT
[Link]("Hello, World!"); // With new line
[Link]("No new line"); // Without new line

// FORMATTED OUTPUT
string name = "Alice";
int age = 15;
double gpa = 3.75;

// String Interpolation ($) - MODERN APPROACH


[Link]($"Name: {name}, Age: {age}, GPA: {gpa}");

// TAKING USER INPUT


[Link]("\nEnter your name: ");
string userName = [Link]();
[Link]("Enter your age: ");
int userAge = [Link]([Link]());

[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

3.4 Conditional Statements

Example 3: IF-ELSE and SWITCH Statements

using System;

namespace ConditionalDemo
{
class Program
{
// ===========================================
// EXAMPLE 3: CONDITIONAL STATEMENTS
// ===========================================

static void Main(string[] args)


{
[Link]("Enter your score (0-100): ");
int score = [Link]([Link]());

// 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]());

if (age >= 18 && hasLicense == true)


{
[Link]("You can rent a car!");
}

// 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

3.5 Loops and Iteration

Example 4: FOR, WHILE, and DO-WHILE Loops

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 + " ");
}

// FOR-EACH (iterate through collection)


[Link]("\n=== FOR-EACH ===");
string[] colors = { "Red", "Green", "Blue" };
foreach (string color in colors)
{
[Link]($"Color: {color}");
}

// WHILE LOOP (pre-test)


[Link]("\n=== WHILE LOOP ===");
int sum = 0;
int count = 1;
while (count <= 5)
{
sum += count;
count++;
}
[Link]($"Sum: {sum}");

// DO-WHILE LOOP (post-test)


[Link]("\n=== DO-WHILE ===");
string password;
do
{
[Link]("Enter password: ");
password = [Link]();
} while (password != "secret");

[Link]("Access granted!");

// BREAK AND CONTINUE


[Link]("\n=== BREAK ===");
for (int i = 1; i <= 10; i++)
{
if (i % 4 == 0)
{
[Link]($"First multiple of 4: {i}");
break;
}
}
}
}
}

// 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

Example 5: Working with Arrays

using System;

namespace ArraysDemo
{
class Program
{
// ===========================================
// EXAMPLE 5: ARRAYS IN C#
// ===========================================

static void Main(string[] args)


{
// Declare and initialize array
int[] numbers = { 10, 20, 30, 40, 50 };

// Access elements
[Link]("First: " + numbers[0]); // 10
[Link]("Last: " + numbers[4]); // 50
[Link]("Length: " + [Link]);

// Loop through array


[Link]("\n=== All Numbers ===");
for (int i = 0; i < [Link]; i++)
{
[Link]($"Index {i}: {numbers[i]}");
}

// 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

3.7 Functions and Procedures

Example 6: Methods in C#

using System;

namespace MethodsDemo
{
class Program
{
// ===========================================
// EXAMPLE 6: FUNCTIONS AND PROCEDURES
// ===========================================

static void Main(string[] args)


{
// Call procedure (no return value)
DisplayWelcome();

// Call function (returns a value)


int sum = Add(5, 3);
[Link]($"5 + 3 = {sum}");

int product = Multiply(4, 6);


[Link]($"4 x 6 = {product}");

// Use parameterized method


GreetUser("John");

// Array with method


int[] nums = { 45, 23, 67, 89, 12 };
int max = FindMaximum(nums);
[Link]($"Maximum: {max}");
}

// PROCEDURE: No return value


static void DisplayWelcome()
{
[Link]("================================");
[Link](" WELCOME TO COMPUTER SCIENCE ");
[Link]("================================");
}

// FUNCTION: Returns an integer


static int Add(int a, int b)
{
return a + b;
}
static int Multiply(int x, int y)
{
return x * y;
}

static void GreetUser(string name)


{
[Link]($"Hello, {name}!");
}

static int FindMaximum(int[] arr)


{
int max = arr[0];
foreach (int num in arr)
{
if (num > max) max = num;
}
return max;
}
}
}

// 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

3.8 File Handling

Example 7: Reading and Writing Files

using System;
using [Link];

namespace FileHandlingDemo
{
class Program
{
// ===========================================
// EXAMPLE 7: FILE HANDLING OPERATIONS
// ===========================================

static void Main(string[] args)


{
string filePath = "[Link]";

// WRITE TO FILE
[Link]("Enter text to save: ");
string text = [Link]();
[Link](filePath, text);
[Link]("Data saved!");

// READ FROM FILE


if ([Link](filePath))
{
string content = [Link](filePath);
[Link]($"File content: {content}");
}

// 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!");

// READ ALL LINES


string[] allLines = [Link](filePath);
[Link]($"Total lines: {[Link]}");

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

3.10 Exam Questions

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

Time: 3 Hours | Total Marks: 100

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]

(b) Write SQL statements to: [12 marks]


(i) Create a table called 'Products' with fields: ProductID (PK), ProductName, Price
(ii) Insert two records
(iii) Update the Price
(iv) Delete a product

(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]

(b) Write a C# program that: [10 marks]


(i) Declares an array of 5 integers
(ii) Accepts input to populate the array
(iii) Calculates and displays the sum and average

(c) Write a function that accepts two integers and returns their greatest common divisor (GCD). [9
marks]

EXAMINATION PAPER 2

Time: 3 Hours | Total Marks: 100

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]

(b) Write SQL queries for: [10 marks]


(i) Show all customers from 'Harare'
(ii) Count orders per customer
(iii) Find products with price greater than average

(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]

(b) Write a complete C# program that: [10 marks]


(i) Creates an array of 5 strings
(ii) Uses foreach to display each name
(iii) Searches for a specific name

(c) Write a recursive function to calculate factorial. [9 marks]

EXAMINATION PAPER 3

Time: 3 Hours | Total Marks: 100

QUESTION 1: ALGORITHMS (25 marks)(a) (i) What is meant by 'iteration' in algorithms? [2


marks]
(ii) Compare FOR and WHILE loops. [4 marks]

(b) Write pseudocode for: [8 marks]


(i) Multiplication table for a number (1-10)
(ii) Count vowels in a string

(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

(c) Explain referential integrity and why it is important. [5 marks]

QUESTION 3: PROGRAMMING (25 marks)(a) (i) What is the purpose of comments? [2 marks]
(ii) Write code demonstrating good commenting. [5 marks]

(b) Write a C# program that: [10 marks]


(i) Creates a 3x3 array
(ii) Accepts input to populate
(iii) Displays in matrix format
(iv) Calculates diagonal sum

(c) Explain passing by value vs passing by reference with code examples. [8 marks]

EXAMINATION PAPER 4

Time: 3 Hours | Total Marks: 100

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]

(b) Write pseudocode for: [8 marks]


(i) Accept 5 test scores
(ii) Calculate average
(iii) Display pass/fail for each

(c) Why are indentation and comments important? [7 marks]

QUESTION 2: DATABASE SYSTEMS (25 marks)(a) (i) What is a relational database? [3 marks]
(ii) List three types of relationships. [6 marks]

(b) Write SQL to: [10 marks]


(i) Create 'SchoolDB' database
(ii) Create 'Students' table
(iii) Add 'Email' column
(iv) Create 'Subjects' table
(v) Create 'Enrollments' linking table

(c) What is an index? How does it improve performance? [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

(c) Explain: Array, Function, Loop with code examples. [9 marks]

EXAMINATION PAPER 5

Time: 3 Hours | Total Marks: 100

QUESTION 1: ALGORITHMS AND PROBLEM SOLVING (25 marks) (a) (i) Define pseudocode. [2
marks]
(ii) List three advantages of writing pseudocode. [3 marks]

(b) Write pseudocode for: [10 marks]


(i) Accept username and password
(ii) Validate password is 8+ chars
(iii) Display Access Granted/Denied

(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]

(b) Write SQL for: [12 marks]


(i) Create 'Inventory' table
(ii) Insert 3 products
(iii) Calculate total value
(iv) Find qty < 10
(v) Update quantity

(c) Explain DELETE vs TRUNCATE. [6 marks]


QUESTION 3: PROGRAMMING IN C# (25 marks)(a) (i) [Link]() vs Convert.ToInt32()? [3 marks]
(ii) What happens when parsing non-numeric string? [2 marks]

(b) Write a calculator with: [12 marks]


(i) Menu: Add, Subtract, Multiply, Divide
(ii) Accept two numbers
(iii) Perform operation using switch
(iv) Handle division by zero

(c) Write function that: [8 marks]


(i) Accepts integer array
(ii) Returns largest value
(iii) Uses foreach loop

END OF DOCUMENT

You might also like