TECHNICAL UNIVERSITY OF MOMBASA
School of Computing and Informatics
UNIT CODE: IT/CU/ICT/CR/10/6
COMPUTER PROGRAMMING
COMPREHENSIVE STUDY NOTES
Duration of Unit: 300 Hours | All 6 Learning Outcomes Covered
TVET CDACC © 2024
UNIT 1: PROGRAM AND PROGRAMMING CONCEPTS
1.1 Definition of a Program and Programming
Program: A program is a set of precise, ordered instructions written in a programming language that
a computer's CPU executes to perform a specific task or solve a problem. Programs are stored in
memory and can be executed repeatedly.
Programming: Programming (also called software development or coding) is the art and science of
designing, writing, testing, and maintaining the instructions that make up a computer program. It
involves translating a human problem into a language the machine can understand and act upon.
Source Code: The human-readable form of a program, written by a programmer in a high-level
language (e.g., C, Java, Python). Source code must be translated into machine code before the CPU
can execute it.
Machine Code: Binary instructions (sequences of 0s and 1s) that the CPU directly understands and
executes. Machine code is processor-specific.
KEY POINT: A programmer is essentially a translator — translating a human problem (e.g., 'I need
to calculate monthly payroll') into precise instructions the machine can follow.
1.2 Program Structure
Every well-written program has a clear, consistent structure regardless of the language used. The
three universal sections are:
Section Description and Purpose
Program Header (Documentation The opening section containing comments that document
Block) the program for human readers. Typically includes:
Section Description and Purpose
Program name and purpose, Author's name, Date written,
Version number, and a description of inputs and outputs.
The compiler/interpreter ignores these comments — they
exist purely for programmers.
Declarations Section Where all variables, constants, and data types are
declared before they are used. Declaring variables upfront
gives the program a complete inventory of all the
'containers' it will need. Some languages (like C) require
all declarations at the top; others (like Python) allow
declaration anywhere.
Main Body (Executable Section) Where the actual logic of the program lives — the
sequence of statements, loops, decisions, and function
calls that accomplish the program's goal. This is what runs
when the program is executed.
Subprograms / Functions / Modules Reusable blocks of code defined outside the main body
that can be called (invoked) from anywhere in the
program. Functions promote code reuse, reduce
duplication, and make the program easier to read, test,
and maintain.
Example — Anatomy of a Simple C Program:
/* ================================================
Program: Grade Calculator
Author: J. Kamau
Date: January 2025
Purpose: Reads a student score and displays grade
================================================ */
#include<stdio.h> /* Library inclusion */
/* --- DECLARATIONS --- */
int score; /* Variable: stores the student's score */
char grade; /* Variable: stores the calculated grade */
/* --- MAIN BODY --- */
int main() {
printf("Enter score: ");
scanf("%d", &score);
if (score >= 70) grade = 'A';
else if (score >= 60) grade = 'B';
else if (score >= 50) grade = 'C';
else grade = 'F';
printf("Grade: %c\n", grade);
return 0;
}
1.3 Variable Declaration
A variable is a named location in the computer's RAM (memory) used to store a value that can
change during program execution. A constant is similar but its value cannot change once set.
Rules for naming variables (identifiers):
• Must begin with a letter or underscore (_), never a digit.
• Can contain letters, digits, and underscores — no spaces or special characters.
• Cannot use reserved keywords (e.g., int, while, if).
• Are case-sensitive in most languages: score and Score are different variables.
• Should be meaningful: studentScore is better than x.
Data Type Size (typical) Description and Example
int 4 bytes Whole numbers (no decimal point).
Example: int age = 25;
float 4 bytes Single-precision decimal numbers.
Example: float price = 99.99;
double 8 bytes Double-precision decimal (more
accurate). Example: double pi =
3.14159265;
char 1 byte A single character. Example: char
grade = 'A';
bool 1 byte Logical value: true or false. Example:
bool isActive = true;
string Variable A sequence of characters. Example:
string name = "Alice";
long 8 bytes Large whole numbers. Example: long
population = 8000000000;
short 2 bytes Small whole numbers (-32768 to
32767). Example: short count = 100;
Declaring Variables in C:
/* Variable declarations */
int studentID = 1001;
float cgpa = 3.75;
char initial = 'J';
const float PI = 3.14159; /* Constant — value cannot change */
1.4 Looping Structures
Loops allow a program to execute a block of code repeatedly without rewriting it. There are three
fundamental loop structures:
1.4.1 The FOR Loop
Used when the number of repetitions is known in advance. The loop initialises a counter, checks a
condition, and updates the counter each iteration.
Syntax (C):
for (initialisation; condition; update) {
/* body — executed while condition is TRUE */
}
Example — Print numbers 1 to 10:
int i;
for(i = 1; i <= 10; i++) {
printf("%d\n", i);
}
1.4.2 The WHILE Loop
Used when the number of repetitions is not known in advance. The condition is checked BEFORE
each iteration. If the condition is false initially, the loop body never executes.
int num = 1;
while(num <= 10) {
printf("%d\n", num);
num++; /* Update — prevents infinite loop */
}
1.4.3 The DO-WHILE Loop
Similar to WHILE, but the condition is checked AFTER each iteration. This guarantees the loop body
executes at least once — even if the condition is false from the start. Useful for input validation
menus.
int num;
do {
printf("Enter a positive number: ");
scanf("%d", &num);
} while(num <= 0); /* Repeat until user enters positive number */
Loop Type Condition Checked Best Used When
for Before each iteration Exact number of repetitions is known
while Before each iteration Repetition count depends on runtime
condition
do-while After each iteration Loop must execute at least once
(e.g., menus, input validation)
1.5 Control Structures
Control structures determine the order in which statements are executed. Without them, code
executes line-by-line from top to bottom.
1.5.1 Sequential Structure
The default. Statements execute one after another in the order they appear. Example: read a value,
compute a result, display the result.
1.5.2 Selection (Decision) Structures
IF / ELSE IF / ELSE
Evaluates a condition and executes different code blocks depending on the outcome.
if(score >= 70) {
printf("Grade A");
} else if(score >= 60) {
printf("Grade B");
} else if(score >= 50) {
printf("Grade C");
} else {
printf("Fail");
}
SWITCH Statement
An efficient alternative to multiple IF-ELSE IF when testing one variable against several specific
values (constants).
switch(dayNumber) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid");
}
Ternary Operator
A compact single-line conditional: condition ? value_if_true : value_if_false
char grade = (score >= 50) ? 'P' : 'F'; /* Pass or Fail */
1.6 Syntax
Syntax refers to the set of rules that govern how valid statements are written in a programming
language — the 'grammar' of the language. Violating syntax rules produces a Syntax Error, which the
compiler or interpreter catches and reports before the program can run.
Syntax Concept Explanation and Example
Statement Terminator Most C-family languages end each statement with a
semicolon (;). Example: int x = 10; — missing the
semicolon causes a syntax error.
Braces / Blocks Curly braces { } group statements into a block. Every
opening { must have a matching closing }.
Keywords Reserved words with predefined meanings that cannot be
used as variable names. Examples: if, while, int, return,
class, void.
Case Sensitivity In C, C++, Java, and Python — variable names are case-
sensitive. int Score and int score are two different
variables.
Parentheses Used to enclose conditions in if and while, and arguments
in function calls. Example: if (x > 0) — the parentheses
Syntax Concept Explanation and Example
are mandatory.
Comments Non-executable text for documentation. C uses /* multi-
line */ or // single-line comments.
1.7 Programming Languages and Paradigms
A programming paradigm is a fundamental style or approach to programming that defines how a
programmer structures and thinks about code. Different paradigms suit different types of problems.
Paradigm Description, Key Concepts, and Example Languages
Imperative / Procedural The oldest paradigm. The programmer explicitly states
HOW to solve the problem step by step. Code is a
sequence of statements that change the program's state.
Key concepts: variables, loops, conditionals,
functions/procedures. Examples: C, COBOL, FORTRAN,
Pascal.
Object-Oriented (OOP) Organises code around 'objects' — bundles of data
(attributes) and behaviour (methods) that model real-world
entities. Key concepts: Classes, Objects, Inheritance,
Encapsulation, Polymorphism, Abstraction. Examples:
Java, C++, C#, Python, Ruby.
Functional Treats computation as the evaluation of mathematical
functions. Avoids changing state and mutable data.
Programs are built by composing pure functions. Key
concepts: immutability, higher-order functions, recursion,
lambda expressions. Examples: Haskell, Erlang, Lisp,
Clojure. (Python and JavaScript support functional style
too.)
Declarative The programmer states WHAT the result should be, not
HOW to compute it. The language/runtime figures out the
implementation. Examples: SQL (query a database),
HTML (describe a webpage), CSS (describe styling),
Prolog (logic programming).
Event-Driven Program flow is determined by events (user actions,
sensor signals, messages). Used extensively in GUI
programming and web development. Examples:
JavaScript (in browsers), Visual Basic.
Object-Oriented Programming — The Four Pillars:
1. Encapsulation: Bundling data (attributes) and the methods that operate on that data into a
single unit (class), and restricting direct access to some components. This protects data from
accidental modification. Example: A BankAccount class hides the balance and only allows
access through deposit() and withdraw() methods.
2. Inheritance: A new class (child/subclass) inherits attributes and methods from an existing
class (parent/superclass), enabling code reuse and creating an 'is-a' relationship. Example: A
SavingsAccount class inherits from BankAccount, adding an interest rate attribute.
3. Polymorphism: The ability of different objects to respond to the same method call in different
ways. 'Many forms.' Example: Both a Circle object and a Rectangle object have an area()
method, but each calculates it differently.
4. Abstraction: Hiding complex implementation details and exposing only what is necessary.
The user of a class only needs to know what it does, not how it does it. Example: You use a
car's steering wheel without knowing the internal mechanics of the steering system.
1.8 Approaches to Program Development
A development approach defines the methodology and process used to plan, build, and deliver
software. The main approaches are:
Approach Description, Advantages, and Disadvantages
Waterfall A linear, sequential approach. Each phase must be fully
completed before the next begins: Requirements →
Design → Implementation → Testing → Deployment →
Maintenance. Advantage: Simple to manage; clear
milestones. Disadvantage: Inflexible — changes are costly
once a phase is completed; customer sees no working
software until near the end.
Agile An iterative, incremental approach. Work is broken into
short cycles called sprints (2–4 weeks). Working software
is delivered at the end of each sprint. The customer is
involved throughout. Advantage: Highly flexible; rapid
delivery; continuous feedback. Disadvantage: Scope can
expand uncontrollably; requires active customer
participation.
Spiral Combines Waterfall's structure with Agile's iteration, with a
strong focus on risk analysis at each cycle. Each spiral
completes: Planning → Risk Analysis → Engineering →
Evaluation. Advantage: Best for large, high-risk projects.
Disadvantage: Complex and expensive; requires risk
expertise.
Prototyping A working model (prototype) of the system is built quickly,
shown to the user, refined based on feedback, and
repeated until the final system is agreed upon. Advantage:
Excellent for clarifying unclear requirements.
Disadvantage: Users may mistake the prototype for the
final product; can lead to poor code quality if not
managed.
Incremental The system is delivered in pieces (increments). Each
increment is a fully working subset of the system.
Advantage: Users get working software early; easy to
prioritise features. Disadvantage: Requires careful upfront
architecture planning to ensure increments integrate
correctly.
UNIT 2: PHASES OF PROGRAM DEVELOPMENT
2.1 Overview
Developing a program is not simply about sitting down and writing code. Professional software
development follows a disciplined, structured process to ensure the final product is correct, reliable,
maintainable, and meets the user's needs. This process is called the Program Development Cycle (or
Software Development Life Cycle — SDLC).
Phase Goal, Activities, and Key Outputs
1. Planning Establish WHY the system is needed and WHETHER it is
feasible to build. Activities: Define the problem, set
objectives and scope, conduct feasibility study (technical,
economic, operational, schedule), identify stakeholders,
estimate budget and timeline. Output: Project plan,
feasibility report.
2. System Analysis and Design Determine WHAT the system must do (Analysis) and
HOW it will do it (Design). Analysis Activities: Study the
current system, interview users, gather requirements,
define inputs/outputs. Design Activities: Create DFDs,
flowcharts, pseudocode, database schemas, UI
wireframes. Output: System Requirements Specification
(SRS), design documents.
3. System Development (Coding) Write the actual source code based on the design
specifications. Activities: Choose programming language,
set up development environment, write and review code
for all modules, write internal documentation (comments).
Output: Source code, compiled executable.
4. Testing Verify that the program works correctly, efficiently, and
securely. Activities: Unit testing (individual modules),
integration testing (modules together), system testing
(entire program), user acceptance testing (real users).
Output: Test reports, bug reports, debugged and verified
software.
5. Implementation (Deployment) Release the working program to end users. Activities:
Install software, convert/migrate existing data, train users,
write user manuals, plan the changeover strategy (direct,
parallel, phased, or pilot). Output: Installed operational
system, trained users, user documentation.
KEY POINT: These phases are not always strictly sequential. In Agile development, phases
overlap and repeat. In Waterfall, they are completed one at a time. Understanding the purpose of
each phase is more important than memorising a fixed sequence.
2.2 Planning Phase — Detail
The planning phase determines the project's viability before any significant resources are committed.
A feasibility study examines four dimensions:
5. Technical Feasibility: Does the required technology exist? Is it available to the organisation?
Do we have the technical skills in-house? Example: Can our existing server infrastructure
support a real-time inventory system?
6. Economic Feasibility (Cost-Benefit Analysis): Do the benefits of the new system justify its
costs? Costs include: development, hardware, training, and maintenance. Benefits include:
time savings, error reduction, increased revenue. If Benefits > Costs → economically feasible.
7. Operational Feasibility: Will the users actually use the system? Is the organisation ready for
the change? Will the new system fit into existing workflows and culture?
8. Schedule Feasibility: Can the system be built within the required timeframe? Is the deadline
realistic given the project's complexity and available resources?
2.3 Analysis and Design Phase — Detail
This critical phase has two distinct sub-phases:
System Analysis — understanding the problem:
• Gather information through interviews, questionnaires, observation, and document review.
• Model the current (as-is) system to understand its strengths and weaknesses.
• Define functional requirements (what the system must do) and non-functional requirements
(performance, security, reliability).
• Prioritise requirements with stakeholders.
System Design — creating the solution blueprint:
• Produce Data Flow Diagrams (DFDs) showing how data moves through the system.
• Write pseudocode or draw flowcharts for each algorithm.
• Design the database schema (tables, relationships, keys).
• Design user interface (UI) screens and forms.
• Specify file organisation and data structures.
• Produce the Software Requirements Specification (SRS) document.
2.4 Implementation Phase — Detail
Deploying a new system to users is a critical and risk-laden phase. Four changeover strategies are
used:
Strategy Description, Advantage, and Risk
Direct Changeover The old system is shut down and the new system goes
live simultaneously. Advantage: Simple and inexpensive.
Risk: Highest risk — if the new system fails, there is no
fallback.
Parallel Running Both old and new systems operate simultaneously for a
period. Outputs are compared. Advantage: Safest — old
system is backup. Risk: Expensive and labour-intensive
(double the work).
Phased Implementation Introduce the new system one module or department at a
time. Advantage: Limits risk to small areas. Risk:
Strategy Description, Advantage, and Risk
Integration between old and new system portions can be
complex.
Pilot Implementation Deploy to one location first. If successful, roll out to all.
Advantage: Real-world testing with limited exposure. Risk:
Pilot site may not represent all other locations.
UNIT 3: PROGRAM DESIGN AND ANALYSIS
3.1 Definition
Program Design: The process of creating a detailed, structured plan (blueprint) for a program before
any code is written. It defines the program's structure, data flows, algorithms, and interfaces.
Program Analysis: The process of thoroughly understanding a problem — breaking it down into its
component parts, identifying inputs, processes, outputs, and constraints — before designing a
solution.
KEY POINT: 'Weeks of programming can save hours of planning.' A well-designed program is
significantly faster to implement, test, and maintain than one written without a plan.
3.2 Program Design Tools
Several standardised tools help analysts and programmers plan and communicate program logic
visually and textually:
3.2.1 Data Flow Diagrams (DFDs)
A DFD is a graphical model that shows HOW data moves through a system — where it originates
(external entities), what transformations it undergoes (processes), where it is stored (data stores),
and where it goes (outputs to external entities). DFDs are language-independent and technology-
neutral.
Symbol Name and Meaning
Rectangle External Entity — a person, organisation, or system
outside the program that sends or receives data. Example:
'Student', 'Bank'.
Arrow (→) Data Flow — shows the movement and direction of data.
Labelled with the name of the data (e.g., 'Student Record',
'Invoice').
Circle / Rounded Box Process — a function or transformation that acts on input
data to produce an output. Labelled with a number and a
verb phrase (e.g., '1.0 Validate Login').
Open Rectangle (two lines) Data Store — a repository of data at rest (e.g., 'Student
Database', 'Payroll File'). Labelled D1, D2, etc.
DFD Levels:
• Level 0 (Context Diagram): Shows the entire system as ONE process bubble with all
external entities and major data flows. Provides the bird's-eye view.
• Level 1: Explodes the single process into its major sub-processes, showing internal data
flows and data stores.
• Level 2+: Further decomposes each Level 1 process into greater detail until each process is
simple enough to describe in one page of pseudocode.
3.2.2 Pseudocode
Pseudocode is a structured, informal description of an algorithm written using plain English
vocabulary but the structural conventions of a programming language. It is language-independent —
it can be translated into any programming language.
Pseudocode Rules:
• Keywords are capitalised: START, END, READ, PRINT, IF, THEN, ELSE, ENDIF, WHILE,
ENDWHILE, FOR, ENDFOR, CALL.
• Use indentation to show nesting and hierarchy.
• Be precise and unambiguous — every step must be clear.
• Do not use programming language syntax (no semicolons, braces, or language keywords).
Example — Pseudocode for a payroll calculator:
START
READ employee_name, hours_worked, hourly_rate
IF hours_worked > 40 THEN
overtime_pay = (hours_worked - 40) * hourly_rate * 1.5
gross_pay = (40 * hourly_rate) + overtime_pay
ELSE
gross_pay = hours_worked * hourly_rate
ENDIF
tax = gross_pay * 0.16
net_pay = gross_pay - tax
PRINT employee_name, gross_pay, tax, net_pay
END
3.2.3 HIPO Diagram (Hierarchy plus Input-Process-Output)
HIPO is a documentation technique that combines a hierarchical (top-down) decomposition chart with
detailed IPO (Input-Process-Output) descriptions for each module.
A HIPO diagram consists of two parts:
9. Visual Table of Contents (VTOC): A tree diagram showing the program's module hierarchy
— how the program breaks down into functions and sub-functions from top (most general) to
bottom (most specific).
10. IPO Charts: A separate chart for each module showing: its Inputs (data coming in), its
Processing steps (what it does), and its Outputs (data going out).
Module Name Inputs Outputs
Calculate Gross Pay hours_worked, hourly_rate gross_pay
Calculate Tax gross_pay, tax_rate tax_amount
Module Name Inputs Outputs
Calculate Net Pay gross_pay, tax_amount net_pay
Print Payslip employee_name, gross_pay, Formatted payslip on screen
tax_amount, net_pay
3.2.4 Structure Charts (Structure Diagrams)
A Structure Chart is a top-down diagram that shows the program's modular hierarchy and the data
(parameters) passed between modules (functions). It is derived from DFDs and shows WHAT each
module does and how modules communicate — but NOT the internal logic of each module (that is
shown in pseudocode).
Key notation on structure charts:
• Rectangles: Each rectangle represents one module (function/procedure).
• Arrows between modules: Show the calling relationship — a parent module calls a child
module.
• Small circles on arrows: Represent data couples — data passed between modules. An
open circle = data; a filled circle = control flag.
• Looping arrow: Indicates a module is called repeatedly (in a loop).
• Diamond symbol: Indicates a conditional call (the module is called only under certain
conditions).
3.3 Software Design Levels
Design Level Description
Architectural Design (High-Level) Defines the overall structure of the software system —
how major components/subsystems are organised and
how they interact. Equivalent to the blueprint of a
building's structural framework. Example: Three-tier
architecture (Presentation Layer, Business Logic Layer,
Data Layer).
High-Level Design Breaks the architectural design into major modules and
defines the purpose, inputs, and outputs of each module.
Shows the module hierarchy (structure chart) and major
data flows between modules.
Detailed Design (Low-Level Design) Specifies the internal logic of each individual module: the
exact algorithm, data structures, variable names, and
pseudocode. This is what the programmer translates
directly into code.
3.4 Types of System Design
Design Type Description and Example
Form Design Designing the input and output forms that users interact
with. Principles: clear labels, logical tab order, appropriate
field sizes, clear error messages, consistent layout.
Example: Designing a student registration form — which
fields to include, their order, and validation rules.
Design Type Description and Example
File Organisation Design Deciding how data records will be stored and accessed in
files: Serial, Sequential, Direct (hashed), or Indexed
Sequential. The choice affects performance and the types
of access needed (batch vs. real-time). See Unit 5 in SAD
notes for full detail.
Database Design Creating the relational database schema: identifying
entities, their attributes, primary keys, foreign keys, and
relationships. Applying normalisation (1NF, 2NF, 3NF) to
eliminate redundancy. Example: Designing tables for a
library management system — Books, Members, Loans.
UNIT 4: DEVELOP A COMPUTER PROGRAM — C LANGUAGE
4.1 Format of a Computer Program
Every computer program, regardless of language, must have a predictable structure that the compiler
can process. In C, the standard format is:
/* ===================================================
PROGRAM HEADER — Documentation block (comments)
Program: Student Result Calculator
Author: Alice Wanjiku
Date: February 2025
=================================================== */
#include<stdio.h> /* Standard I/O library */
#include<string.h> /* String functions library */
#define MAX_SCORE 100 /* Constant using preprocessor */
/* === GLOBAL DECLARATIONS === */
int totalStudents = 0;
float classAverage;
/* === FUNCTION PROTOTYPE (forward declaration) === */
char calculateGrade(float score);
/* === MAIN BODY === */
int main() {
/* Program logic goes here */
return 0;
}
/* === SUB-PROGRAM (user-defined function) === */
char calculateGrade(float score) {
if(score >= 70) return 'A';
else if(score >= 60) return 'B';
else if(score >= 50) return 'C';
else return 'F';
}
4.2 The C Language — Structure and Special Features
C is a general-purpose, procedural, compiled language developed by Dennis Ritchie at Bell Labs
(1972). It remains foundational — C is used for operating systems (Linux, Windows kernel), device
drivers, embedded systems, and is the basis for C++, Java, and C#.
Special Features of C:
• Compiled: C code is compiled into efficient machine code — programs run very fast.
• Portable: C code can be compiled on different hardware platforms with minimal changes.
• Low-level access: C can directly access memory addresses (using pointers) — essential for
systems programming.
• Rich library: The C Standard Library provides ready-made functions for I/O, maths, strings,
and more.
• Structured: Encourages modular programming through functions.
• Weakly typed: The programmer must explicitly declare types but can convert between them.
4.3 Variables and Constants in C
/* --- VARIABLE DECLARATION SYNTAX: data_type variable_name = value; --- */
int age = 20; /* Integer */
float salary = 45500.75; /* Single-precision float */
double pi = 3.14159265358; /* Double-precision float */
char initial = 'J'; /* Single character */
char name[50]; /* String (array of chars) */
/* --- CONSTANTS --- */
const float TAX_RATE = 0.16; /* Using const keyword */
#define DAYS_IN_WEEK 7 /* Using preprocessor macro */
4.4 Input / Output Functions in C
Function Purpose and Syntax
printf() Prints formatted output to the screen. printf("format string",
variables); Format specifiers: %d (integer), %f (float), %c
(character), %s (string), %lf (double). Example:
printf("Name: %s, Age: %d\n", name, age);
scanf() Reads formatted input from the keyboard. Uses &
(address-of operator) for most types. scanf("%format",
&variable); Example: scanf("%d %f", &age, &salary);
gets() / fgets() Reads an entire line of text (string) including spaces.
fgets(name, 50, stdin); — safer than gets().
puts() Prints a string followed by a newline. puts("Hello World");
getchar() / putchar() Read/write a single character. char ch = getchar();
4.5 Identifiers, Reserved Words, and Literals
An identifier is any name given by the programmer to a variable, function, or constant. An identifier
must follow the naming rules described in Unit 1.
Reserved Keywords in C (cannot be used as identifiers):
auto break case char const continue default do double else enum extern
float for goto if int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
Literals are fixed values written directly in the code:
• Integer literals: Whole number values: 25, -100, 0
• Floating-point literals: Decimal values: 3.14, -0.5, 2.0e6
• Character literals: Single characters in single quotes: 'A', '7', '\n' (newline)
• String literals: Text in double quotes: "Hello, World!"
4.6 Data Types and Their Sizes in C
Data Type Size (32-bit system) Range / Description
char 1 byte -128 to 127 (or 0 to 255 unsigned).
Stores a single character.
short int 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
long int 4 or 8 bytes -2^31 to 2^31-1 (4 bytes) or larger
float 4 bytes ~6-7 significant decimal digits. ±3.4 ×
10^38
double 8 bytes ~15-16 significant decimal digits. ±1.7
× 10^308
long double 12 or 16 bytes Extended precision floating point.
void 0 bytes Represents absence of a type. Used
for functions with no return value.
_Bool (bool) 1 byte 0 (false) or 1 (true). Include
<stdbool.h> for bool keyword.
4.7 Conditional Statements (Full Detail)
Complete example — student grade calculator with all conditions:
#include<stdio.h>
int main() {
float score;
char grade;
printf("Enter exam score (0-100): ");
scanf("%f", &score);
if(score < 0 || score > 100) {
printf("Error: Invalid score!\n");
} else if(score >= 70) {
grade = 'A'; printf("Distinction\n");
} else if(score >= 60) {
grade = 'B'; printf("Credit\n");
} else if(score >= 50) {
grade = 'C'; printf("Pass\n");
} else {
grade = 'F'; printf("Fail\n");
}
printf("Grade: %c\n", grade);
return 0;
}
4.8 Loop Control in C — Advanced
Loop control statements alter the normal flow of loop execution:
• break: Immediately terminates the nearest enclosing loop or switch statement. Execution
continues with the statement after the loop/switch.
• continue: Skips the rest of the current loop iteration and jumps to the next iteration (back to
the condition check).
• goto: Jumps unconditionally to a labelled statement. Rarely used — considered poor practice
as it makes code hard to follow.
Example — Finding the first prime number in a range:
int i, j, isPrime;
for(i = 2; i <= 100; i++) {
isPrime = 1;
for(j = 2; j < i; j++) {
if(i % j == 0) {
isPrime = 0;
break ; /* Exit inner loop — no need to check further */
}
}
if(isPrime) { printf("%d is prime\n", i); break; } /* First prime found */
}
Example — Skip even numbers using continue:
int i;
for(i = 1; i <= 20; i++) {
if(i % 2 == 0) continue; /* Skip even numbers */
printf("%d ", i); /* Only prints odd numbers */
}
4.9 C Functions — Library and User-Defined
A function is a named, reusable block of code that performs a specific task. Functions are the building
blocks of structured C programs.
4.9.1 Library Functions (Built-in)
Library / Header Key Functions Description
<stdio.h> printf(), scanf(), fgets(), fopen(), Standard Input/Output: screen,
fclose(), fprintf(), fscanf() keyboard, and file operations.
<math.h> sqrt(), pow(), abs(), ceil(), Mathematical functions. Compile with
floor(), sin(), cos(), log() -lm flag.
<string.h> strlen(), strcpy(), strcat(), String manipulation functions.
strcmp(), strchr(), strstr()
<stdlib.h> malloc(), free(), rand(), srand(), Memory allocation, random numbers,
atoi(), atof(), exit() type conversion.
<ctype.h> isalpha(), isdigit(), isupper(), Character classification and
tolower(), toupper() conversion.
<time.h> time(), clock(), difftime(), Date and time functions.
strftime()
4.9.2 User-Defined Functions
Syntax: return_type function_name(parameter_list) { body }
Complete example — Functions with arguments and return values:
#include<stdio.h>
/* Function prototype — must appear before main() or the function itself */
float calculateAverage(float a, float b, float c);
void displayResult(float avg);
int main() {
float m1, m2, m3, avg;
printf("Enter 3 marks: ");
scanf("%f %f %f", &m1, &m2, &m3);
avg = calculateAverage(m1, m2, m3); /* Function call */
displayResult(avg);
return 0;
}
/* Function definition — receives 3 floats, returns 1 float */
float calculateAverage(float a, float b, float c) {
return(a + b + c) / 3.0;
}
/* void function — returns nothing, just displays */
void displayResult(float avg) {
printf("Average: %.2f\n", avg);
if(avg >= 50)
printf("Result: PASS\n");
else
printf("Result: FAIL\n");
}
Arguments vs Parameters:
• Parameters: The variable names in the function definition. They act as placeholders.
Example: float a, float b, float c in calculateAverage.
• Arguments: The actual values passed to the function when it is called. Example: m1, m2, m3
in calculateAverage(m1, m2, m3).
• Pass by Value: In C, function arguments are passed by value by default — the function
receives a copy of the value. Changes inside the function do not affect the original variable.
• Pass by Reference (using pointers): Passing the address of a variable (&variable) allows
the function to modify the original. Example: scanf uses & — scanf("%d", &age) passes the
address of age.
UNIT 4 (CONTINUED): OBJECT-ORIENTED PROGRAMMING USING
JAVA
4.10 Introduction to Java and OOP
Java: A high-level, class-based, object-oriented programming language developed by Sun
Microsystems (1995), now maintained by Oracle. Java is famous for its 'Write Once, Run Anywhere'
(WORA) principle.
Java Virtual Machine (JVM): The JVM is the engine that runs Java programs. Instead of compiling
directly to machine code, the Java compiler (javac) produces platform-neutral bytecode (.class files).
The JVM on the target machine interprets and executes this bytecode. This is why Java is platform-
independent.
Java Libraries (Java API): Java comes with an extensive standard class library (Application
Programming Interface) providing thousands of ready-made classes for I/O, networking, data
structures, graphics, and more. Key packages: [Link] (core), [Link] (utilities, Scanner, ArrayList),
[Link] (file I/O).
The Java Compilation and Execution Process:
• Step 1 — Write: Programmer writes source code in a .java file (e.g., [Link]).
• Step 2 — Compile: The javac compiler translates .java source code to .class bytecode.
• Step 3 — Run: The JVM on the target machine loads and executes the .class bytecode.
KEY POINT: Java bytecode is NOT machine code. It is an intermediate language that any JVM on
any operating system can execute — this is the source of Java's portability.
4.11 Java Program Structure
// [Link] — Basic Java program structure
public class HelloWorld { // Class declaration
// Main method — entry point of every Java program
public static void main(String[] args) {
// Java Output
[Link]("Hello, World!"); // prints with newline
[Link]("No newline here "); // prints without newline
[Link]("Pi = %.2f%n", 3.14159); // formatted output
} // end main
} // end class
Every Java program must have:
• A public class whose name exactly matches the filename (case-sensitive).
• A main method with the exact signature: public static void main(String[] args)
• All code inside a class — Java has no standalone functions, only methods.
4.12 Variables, Expressions, and Data Types in Java
Type Size Range / Notes
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2^31 to 2^31-1 (most common
integer type)
Type Size Range / Notes
long 8 bytes -2^63 to 2^63-1. Literal suffix L: long x
= 9876543210L;
float 4 bytes ~7 decimal digits. Suffix f: float f =
3.14f;
double 8 bytes ~15 decimal digits (default for
decimals in Java)
char 2 bytes A single Unicode character in single
quotes: char c = 'A';
boolean 1 bit true or false only
String Object Not a primitive — it's a class.
Immutable sequence of characters.
String s = "Hello";
Variable declaration and expressions:
int age = 21;
double salary = 55000.50;
boolean isStudent = true;
String name = "Alice Kamau";
final double PI = 3.14159; // 'final' = constant in Java
// Arithmetic expressions
int result = (age * 2) + 10; // 52
double area = PI * 5.0 * 5.0; // circle area
String fullGreeting = "Hello " + name; // String concatenation with +
4.13 Input in Java (Scanner Class)
import [Link]; // Import the Scanner class
public class InputDemo {
public static void main(String[] args) {
// Create a Scanner object connected to keyboard input
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link](); // Read full line
[Link]("Enter your age: ");
int age = [Link](); // Read integer
[Link]("Enter your salary: ");
double salary = [Link](); // Read decimal
[Link]("Name: %s, Age: %d, Salary: %.2f%n", name, age,
salary);
[Link](); // Good practice: close Scanner when done
}
}
4.14 Boolean Statements and Operators in Java
Operator / Concept Example and Result
Comparison Operators == (equal), != (not equal), > (greater), < (less), >= (greater
or equal), <= (less or equal). Example: int x = 10; boolean
result = (x > 5); // true
Logical AND (&&) Both conditions must be true. Example: if (age >= 18 &&
hasID) — only passes if BOTH are true.
Logical OR (||) At least one condition must be true. Example: if (isMember
|| hasCoupon) — passes if either is true.
Logical NOT (!) Reverses the boolean value. Example: if (!isLoggedIn) —
executes if user is NOT logged in.
Short-Circuit Evaluation In &&, if the first condition is false, the second is not
evaluated. In ||, if the first is true, the second is skipped.
This prevents errors like null pointer exceptions.
Boolean example — login validation:
String username = "admin";
String password = "secure123";
boolean isValid = [Link]("admin") && [Link]() >= 8;
if(isValid) {
[Link]("Login successful!");
} else {
[Link]("Invalid credentials!");
}
4.15 Loops and Program Flow in Java
Java supports the same three loop structures as C (for, while, do-while) plus enhanced for-each for
arrays and collections:
For Loop:
for(int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
While Loop — password retry:
int attempts = 0;
String password = "";
while( && attempts < 3) {
[Link]("Enter password: ");
password = [Link]();
attempts++;
}
Enhanced For-Each loop:
int[] scores = {85, 72, 91, 64, 78};
for(int score : scores) {
[Link](score); // Iterates over every element
}
4.16 Classes and Objects in Java
The class is the fundamental building block of Java. A class is a blueprint or template; an object is a
specific instance created from that blueprint.
// == CLASS DEFINITION ==
public class Student {
// === ATTRIBUTES (Instance Variables) ===
private String name;
private int studentID;
private double cgpa;
// === CONSTRUCTOR — called when object is created ===
public Student(String name, int studentID, double cgpa) {
[Link] = name; // 'this' refers to current object
[Link] = studentID;
[Link] = cgpa;
}
// === METHODS (Behaviours) ===
public void displayInfo() {
[Link]("ID: %d Name: %s CGPA: %.2f%n",
studentID, name, cgpa);
}
public boolean isHonours() {
return(cgpa >= 3.5);
}
// === GETTERS AND SETTERS (Encapsulation) ===
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public double getCgpa() { return cgpa; }
public void setCgpa(double cgpa) { [Link] = cgpa; }
}
// == USING THE CLASS IN main() ==
public class Main {
public static void main(String[] args) {
// Create objects (instances of Student)
Student s1 = new Student("Alice Kamau", 1001, 3.75);
Student s2 = new Student("Brian Otieno", 1002, 2.90);
[Link](); // Output: ID: 1001 Name: Alice Kamau
CGPA: 3.75
[Link]([Link]()); // Output: true
[Link]();
[Link](3.60); // Update CGPA using setter
}
}
4.17 Arrays in Java
An array is a fixed-size, ordered collection of elements of the SAME data type, stored in contiguous
memory locations. Elements are accessed by index starting at 0.
One-Dimensional Array:
int[] marks = new int[5]; // Declare array of 5 integers
marks[0] = 85; marks[1] = 72; // Assign values by index
// Shorthand initialisation
double[] prices = {19.99, 49.50, 5.75, 120.00};
// Traverse with for-each
double total = 0;
for(double price : prices) {
total += price;
}
[Link]("Total: KSh %.2f%n", total);
Two-Dimensional Array (Matrix):
int[][] matrix = new int[3][3]; // 3 rows, 3 columns
int[][] grid = {{1,2,3},{4,5,6},{7,8,9}}; // Initialised 2D array
// Traverse 2D array with nested for loops
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 3; col++) {
[Link]("%3d", grid[row][col]);
}
[Link]();
}
4.18 Exception Handling in Java
An exception is an unexpected event that disrupts the normal flow of a program at runtime (e.g.,
dividing by zero, file not found, invalid input). Java provides a robust exception handling mechanism
using try-catch-finally blocks.
public class ExceptionDemo {
public static void main(String[] args) {
// === BASIC TRY-CATCH ===
try {
int result = 100 / 0; // ArithmeticException!
[Link](result);
} catch(ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
[Link]([Link]()); // Print error detail
} finally {
[Link]("This always runs — cleanup code here.");
}
// === MULTIPLE CATCH BLOCKS ===
try {
int[] arr = new int[3];
arr[10] = 5; // ArrayIndexOutOfBoundsException!
} catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds!");
} catch(Exception e) {
[Link]("General error: " + [Link]());
}
// === THROWING A CUSTOM EXCEPTION ===
try {
int age = -5;
if(age < 0) throw new IllegalArgumentException("Age cannot be
negative!");
} catch(IllegalArgumentException e) {
[Link]([Link]());
}
}
}
Common Exception Class When It Occurs
ArithmeticException Division by zero or invalid arithmetic.
NullPointerException Accessing a method or field on a null object reference.
ArrayIndexOutOfBoundsException Accessing an array element with an invalid index.
NumberFormatException Converting a non-numeric string to a number (e.g.,
[Link]("abc")).
ClassCastException Illegal casting between incompatible types.
StackOverflowError Infinite recursion — too many nested method calls.
FileNotFoundException Trying to open a file that does not exist.
UNIT 5: PROGRAM TESTING AND DEBUGGING
5.1 Testing vs Debugging — Key Distinction
Testing: The process of executing a program with the deliberate intention of finding errors (bugs).
Testing is a planned, systematic activity. The tester asks: 'Does the program do what it is supposed to
do?' A test that finds a bug is a successful test.
Debugging: The process of locating, diagnosing, and fixing a specific error after it has been
discovered during testing. Debugging asks: 'Why is this happening, and how do I fix it?' Debugging is
the 'surgery' that follows testing's 'diagnosis.'
Aspect Testing vs Debugging
Goal Testing: Find bugs. Debugging: Fix bugs.
Who does it Testing: Can be done by developers or dedicated QA
Aspect Testing vs Debugging
testers. Debugging: Done by the programmer who wrote
the code.
When Testing happens throughout the SDLC (unit, integration,
system, UAT). Debugging happens in response to test
failures.
Tools Testing: Test frameworks (JUnit, Selenium), test plans.
Debugging: IDE debuggers, print statements, log analysis.
5.2 Types of Testing
Type of Testing Description and Purpose
Smoke Testing A quick, preliminary test of the most critical functions to
determine whether the software is stable enough for more
rigorous testing. Also called 'sanity testing' or 'build
verification testing.' Example: Can the application launch?
Can a user log in?
Functional Testing Verifies that each function of the software operates
according to its specification. Tests inputs, processes, and
outputs against requirements. Example: Does the 'Add to
Cart' button correctly add the item to the cart and update
the total?
Usability Testing Evaluates how easy and intuitive the software is for real
users. Involves observing actual users performing tasks
and noting where they struggle. Focuses on the user
experience (UX) rather than technical correctness.
Security Testing Identifies vulnerabilities and weaknesses in the system's
security controls. Includes: penetration testing (ethical
hacking), SQL injection testing, cross-site scripting (XSS)
testing, and authentication testing.
Performance Testing Evaluates how the system behaves under various load
conditions. Sub-types: Load Testing (normal expected
load), Stress Testing (beyond maximum load to find
breaking point), Endurance/Soak Testing (sustained load
over long period).
Regression Testing Re-runs previously passed tests after any code change,
bug fix, or new feature addition to ensure that existing
functionality has not been broken. Essential in Agile
development where code changes frequently.
Compliance Testing Verifies that the software meets required external
standards, regulations, or contractual obligations.
Example: GDPR compliance (data privacy), PCI-DSS
compliance (payment card security), ISO standards.
5.3 Levels of Testing
Level Description, Scope, and Who Does It
Unit Testing Tests individual functions, methods, or modules in
complete isolation from the rest of the system. Uses mock
objects to simulate dependencies. Done by the developer.
Goal: Confirm each unit of code behaves exactly as
designed. Tools: JUnit (Java), unittest (Python), CUnit (C).
Integration Testing Tests how two or more units work together after individual
unit testing. Identifies interface defects — errors that occur
at the boundaries between modules. Done by developers
or a test team. Approaches: Top-down, Bottom-up, Big
Bang, Sandwich.
System Testing Tests the entire, fully integrated system as a whole in an
environment that closely mirrors production. Verifies the
system meets all functional and non-functional
requirements in the SRS. Done by an independent testing
team.
Acceptance Testing (UAT) The final testing phase before go-live, conducted by the
actual end users (not the development team). Two sub-
levels: Alpha Testing (done by internal staff in a controlled
environment), Beta Testing (done by real users in a real-
world environment). Goal: Confirm the system is fit for
purpose and ready for deployment.
5.4 Methods of Testing
Method Description and Key Characteristics
Black-Box Testing The tester has NO knowledge of the internal code or
implementation. Tests are based purely on inputs and
expected outputs (the specification). Focuses on WHAT
the system does, not HOW it does it. Good for: Functional
testing, acceptance testing. Limitations: Cannot test code
paths — some logic may never be tested.
White-Box Testing (Clear/Glass Box) The tester has FULL knowledge of the internal code.
Tests are designed to exercise specific code paths,
branches, loops, and conditions. Ensures every statement
and decision in the code is executed at least once. Good
for: Unit testing, security testing. Requires programming
knowledge.
Grey-Box Testing A combination of Black-Box and White-Box. The tester
has partial knowledge of the implementation (e.g., knows
the database schema but not the code). Good for:
Integration testing, web application testing.
Agile Testing Testing is integrated into every sprint rather than being a
separate phase. Developers and testers work together.
Emphasises Test-Driven Development (TDD) — write the
Method Description and Key Characteristics
test before writing the code.
Ad-hoc Testing Informal, unplanned testing with no documentation or test
cases. The tester randomly explores the application trying
to find defects. Also called 'Monkey Testing.' Advantage:
Can find unexpected bugs that formal tests miss.
Limitation: Not repeatable; results are not documented.
5.5 Test Data Categories
When designing test cases, three categories of test data must always be used:
11. Normal/Valid Data: Data within the expected range that the program should process
correctly. Example: For a field accepting ages 1–120, normal data = 25, 45, 67.
12. Boundary/Limit Data: Data at the extreme edges of the valid range (and just outside).
Example: For ages 1–120, boundary data = 0, 1, 2, 119, 120, 121. Boundary Value Analysis
(BVA) is the technique of testing at and around boundaries, as errors most commonly occur
here.
13. Erroneous/Invalid Data: Data that the program should reject with an appropriate error
message. Example: For an age field — negative numbers, letters, symbols, very large
numbers. Tests the program's validation and error-handling.
5.6 Debugging — Steps, Requirements, and Techniques
When a bug is found, professional debugging follows a systematic process:
5.6.1 The Debugging Steps
14. Reproduce: Find the exact input data or sequence of actions that consistently causes the
error to appear. A bug that cannot be reproduced reliably is very difficult to fix.
15. Locate/Isolate: Narrow down where in the code the error occurs. Use print statements, log
messages, or a debugger to identify the exact line or function causing the problem.
16. Analyse: Understand WHY the error is happening. Is it a wrong formula? A missing
condition? An off-by-one error? An unhandled edge case? Do not fix symptoms — find the
root cause.
17. Fix: Correct the code to address the root cause. Make the minimal change needed — avoid
introducing new problems.
18. Regression Test: Re-run all existing tests to confirm: (a) the bug is fixed, and (b) the fix did
not break anything that was previously working.
19. Document: Record the bug, its root cause, and the fix in a bug tracking system (e.g., Jira,
GitHub Issues). This prevents the same bug from occurring again.
5.6.2 Debugging Requirements
• A reliable development environment (IDE with debugging tools).
• Comprehensive test cases that can reproduce the error.
• Access to the source code and understanding of the algorithm.
• Log files and error messages from the system.
• A bug tracking system to manage and prioritise defects.
5.6.3 Debugging Principles
• Understand Before Fixing: Never change code hoping it will fix the bug. Understand the root
cause first.
• One Change at a Time: Make one change and re-test. Multiple simultaneous changes make
it impossible to know which one fixed (or broke) things.
• Work from Evidence: Base conclusions on what the data and logs actually show, not on
assumptions.
• Simplify: Isolate the smallest code fragment that reproduces the bug.
• Take Breaks: Fresh eyes often spot what tired eyes miss.
5.6.4 Debugging Techniques
Technique Description
Print Statement Debugging Insert printf() / [Link]() statements at key
points to display variable values as the program runs.
Simple and effective for small programs.
Interactive Debugger (IDE) Use the IDE's built-in debugger (e.g., in Eclipse, IntelliJ,
VS Code). Set breakpoints (execution pauses at that line),
then step through code line-by-line, inspecting variable
values at each step.
Rubber Duck Debugging Explain your code line-by-line to an inanimate object
(rubber duck). The act of verbalising forces you to think
through the logic carefully, often revealing the error.
Binary Search / Divide and Conquer Comment out or skip half the code. If the bug disappears,
it is in the removed half. Keep halving the code until the
buggy section is isolated.
Logging Replace temporary print statements with a proper logging
framework (e.g., Log4j in Java). Log messages at different
severity levels (DEBUG, INFO, WARN, ERROR) and
review log files.
Code Review (Pair Programming) Have another programmer read through your code. A
fresh perspective often spots logical errors and oversights
that the original author misses.
Trace Table (Dry Run) Manually trace through the algorithm on paper, recording
the value of each variable after every statement.
Particularly useful for finding logic errors in loops and
conditional statements.
Types of Bugs:
• Syntax Error: Violates the grammar rules of the language. Caught by the compiler/interpreter
before the program runs. Example: Missing semicolon in C; misspelled keyword.
• Runtime Error: Occurs while the program is running and causes it to crash. Example:
Division by zero; array index out of bounds; null pointer dereference.
• Logic Error: The program runs without crashing but produces incorrect output. The most
dangerous type — the computer cannot detect it; only testing and human analysis can.
Example: Using + instead of * in a formula; wrong loop termination condition.
• Semantic Error: Code that is syntactically correct but has a meaning the programmer did not
intend. Example: Assigning the wrong variable or using the wrong operator.
UNIT 6: USER TRAINING AND PROGRAM MAINTENANCE
6.1 Identifying User Training Needs
Before designing a training programme, the analyst must assess what users already know and what
they need to learn in order to use the new system effectively. This is called a Training Needs Analysis
(TNA).
Factors that influence training needs:
• Users' existing technical skill level: Novice users need basic computer literacy training in
addition to system training; experienced users may only need system-specific training.
• Complexity of the new system: A simple data-entry system needs less training than a
complex ERP system.
• Degree of change: If the new system is very different from the old one, more training is
required.
• User roles: Different roles need different training. A data-entry clerk needs to know how to
enter records; a manager needs to know how to generate reports; an administrator needs to
know system configuration.
• Number of users and locations: Large, geographically distributed organisations need
scalable training strategies.
Methods for identifying training needs:
• Interviews and questionnaires with potential users.
• Observation of users working with the old system.
• Analysis of job descriptions and workflow requirements.
• Consultation with department managers.
6.2 Methods of User Training
Training Method Description, Advantages, and Best Use
Classroom / Workshop Training Instructor-led, face-to-face training in a classroom or
computer lab. Hands-on practice with the system. Allows
immediate questions and interaction. Best for: Small to
medium groups; complex systems requiring
demonstration. Limitation: Expensive and time-consuming
for large organisations.
Train-the-Trainer A selected group of super users (champions) from each
department are trained intensively. They then train their
colleagues. Best for: Large organisations with many users
— scales efficiently. Limitation: Trainer quality depends on
the super user's teaching ability.
Online / E-learning Self-paced video tutorials, interactive modules, and
quizzes accessible via the internet or intranet. Users can
learn at their own pace and revisit sections. Best for:
Training Method Description, Advantages, and Best Use
Geographically dispersed users; refresher training. Tools:
Moodle, Coursera, custom LMS (Learning Management
System).
User Manuals and Quick Reference Printed or digital documentation covering system usage
Guides step-by-step. Essential reference material after training is
complete. Best for: Ongoing reference; tasks done
infrequently. Limitation: Quickly becomes outdated if the
system changes.
On-the-Job Training (Guided Users learn by doing real tasks with a trainer or super user
Practice) available for immediate guidance. Best for: Simple
systems or follow-up reinforcement after initial training.
Limitation: Disrupts normal work and may slow down
productivity initially.
Simulated/Sandbox Environment Users practise on a copy of the system with dummy data.
They can make mistakes without affecting real data. Best
for: High-risk systems (financial, medical) where live
mistakes are costly.
Webinars and Video Calls Live online sessions where a trainer demonstrates the
system remotely while users follow along on their own
systems. Best for: Remote teams; updates and new
features.
6.3 User Training Manuals
A training/user manual is a document that guides users in operating the software system. It is an
essential component of any system deployment. A well-written user manual reduces training time,
support calls, and user errors.
Components of a good user manual:
20. Introduction: Overview of the system, its purpose, and the intended audience of the manual.
21. Getting Started: System requirements, installation steps (if applicable), and how to launch
the program.
22. Navigation Guide: Explanation of the main screen, menus, toolbars, and navigation
conventions.
23. Task-Based Instructions: Step-by-step instructions for each major task, written from the
user's perspective. Use numbered steps. Include screenshots. Example: 'How to register a
new student' — Step 1: Click 'Students' in the top menu. Step 2: Click 'Add New.' ...
24. Troubleshooting Guide: A list of common error messages and problems with their solutions.
Example: 'If you see Error 401, check your username and password.'
25. Glossary: Definitions of technical terms used in the system and manual.
26. Index: Alphabetical list of topics for quick reference.
Principles of effective manual writing:
• Write for the user's level — avoid jargon for non-technical users.
• Use active voice and clear, short sentences.
• Include annotated screenshots for every significant step.
• Test the manual by having a user follow it without assistance.
• Keep it up to date when the system changes.
6.4 Maintenance Schedule
Software maintenance is the longest and most expensive phase of the software lifecycle. Research
consistently shows that 60–80% of a software product's total lifetime cost is spent on maintenance. A
maintenance schedule ensures that maintenance activities are planned, tracked, and carried out
systematically.
A maintenance schedule should include:
• Type of maintenance activity (corrective, adaptive, perfective, preventive).
• Trigger for the activity (user report, scheduled interval, external change).
• Person or team responsible.
• Estimated effort and priority level.
• Target completion date.
• Testing and sign-off requirements after the change.
Maintenance Type Goal and Trigger
Corrective Fix bugs and errors discovered after deployment.
Triggered by: user bug reports, crash logs, error alerts.
Adaptive Modify the system to work correctly in a changed
environment. Triggered by: OS upgrade, new hardware,
regulatory change, third-party API change.
Perfective Improve performance, add new features, or enhance
usability based on user feedback. Triggered by: user
feature requests, performance monitoring alerts.
Preventive Proactively fix potential future problems before they occur.
Triggered by: scheduled reviews, risk assessments, code
quality analysis (technical debt reduction).
6.5 System Maintenance Tools and Techniques
Tool / Technique Purpose and Examples
Version Control Systems Track all changes to the source code over time; enable
rollback to previous versions; allow multiple developers to
collaborate. Examples: Git (most widely used), Subversion
(SVN), Mercurial. Key concepts: Repository, Commit,
Branch, Merge, Tag.
Bug / Issue Tracking Systems Manage the lifecycle of bugs and change requests from
discovery through fix to closure. Examples: Jira, GitHub
Issues, Bugzilla, Trello. Features: Priority levels, assignee,
status (Open/In Progress/Resolved), comment threads.
Integrated Development Provide code editors, debuggers, refactoring tools, and
Environments (IDEs) build systems in one application. Examples: Eclipse,
IntelliJ IDEA (Java), Visual Studio Code, Code::Blocks
(C).
Tool / Technique Purpose and Examples
Automated Testing Frameworks Enable regression testing to be run automatically after
every code change, ensuring fixes do not break existing
functionality. Examples: JUnit (Java), pytest (Python),
CUnit (C), Selenium (web UI testing).
Code Profilers Analyse the running program to identify performance
bottlenecks — functions that consume excessive CPU
time or memory. Examples: Java VisualVM, gprof (C),
JProfiler.
Database Management Tools Monitor database performance, run queries, optimise
indexes, and manage data backups. Examples: MySQL
Workbench, pgAdmin (PostgreSQL), SQL Developer
(Oracle).
Continuous Integration / Continuous Automate the process of building, testing, and deploying
Deployment (CI/CD) software whenever code is pushed to the repository.
Examples: Jenkins, GitHub Actions, GitLab CI/CD, Travis
CI.
6.6 Monitoring of System Performance
Ongoing monitoring ensures the system continues to meet performance requirements as usage
grows and the environment changes.
Key performance metrics to monitor:
• Response Time: Time between a user's request and the system's response. Acceptable
thresholds vary: web pages should load in under 3 seconds; database queries in milliseconds.
• Throughput: Number of transactions or requests the system can handle per unit time (e.g.,
1000 transactions per second).
• CPU Utilisation: Percentage of CPU time being used. Sustained high CPU (above 80%)
indicates a performance problem.
• Memory Usage: Amount of RAM in use. Growing memory usage over time may indicate a
memory leak.
• Error Rate: Frequency of errors (crashes, exceptions, timeouts) per unit time.
• Disk I/O: Rate of reading and writing to storage. High disk I/O can be a bottleneck for
database-heavy applications.
• Concurrent Users: Number of users accessing the system simultaneously. Load balancing
may be needed as this grows.
Monitoring Tools:
• Server monitoring: Nagios, Zabbix, Prometheus + Grafana.
• Application Performance Monitoring (APM): New Relic, Dynatrace, AppDynamics.
• Log management: ELK Stack (Elasticsearch, Logstash, Kibana), Splunk.
• Database monitoring: MySQL Enterprise Monitor, pg_stat_statements (PostgreSQL).
6.7 Rectification of Bugs (Post-Deployment)
After deployment, bugs are reported by users. A formal bug rectification process ensures they are
handled professionally:
27. Bug Report: User or monitoring system reports a bug. The report includes: description of the
problem, steps to reproduce, severity (Critical/High/Medium/Low), and the environment (OS,
browser, version).
28. Triage: The maintenance team reviews and validates the bug report. They confirm it is
reproducible, assign a priority level, and assign it to the appropriate developer.
29. Root Cause Analysis: Developer investigates to identify the exact cause (not just the
symptom).
30. Fix and Code Review: Developer writes the fix. Another developer reviews the fix to ensure it
is correct and does not introduce new issues.
31. Regression Testing: The fixed version is tested: the specific bug is retested (confirmation
testing) and all related tests are re-run (regression testing).
32. Release and Deploy: The fix is packaged into a patch release and deployed to production
using the organisation's change management process.
33. Close and Document: The bug is closed in the issue tracker with a description of the root
cause and fix.
6.8 Handling Requested Changes
Users frequently request changes to the system after deployment — new features, modified
workflows, or improved usability. These changes must be managed through a formal Change
Management Process to prevent uncontrolled modifications that destabilise the system.
The Change Request Process:
34. Submit Change Request: User or manager submits a formal Change Request (CR)
describing the desired change, its business justification, and urgency.
35. Impact Analysis: The analyst and developer assess the impact of the change: How many
modules are affected? How much development effort is needed? What are the risks? Does it
conflict with existing functionality?
36. Approval / Rejection: A Change Advisory Board (CAB) or project manager reviews the
impact analysis and approves, rejects, or defers the change. This prevents scope creep.
37. Design and Implement: If approved, the change is designed, coded, and documented
following the normal development process.
38. Test: The change is unit tested, integration tested, and regression tested.
39. Deploy: The updated system is deployed using the organisation's standard deployment
procedure.
40. Close CR: The change request is marked as complete and the change is documented in the
system's changelog.
UNIT SUMMARY — QUICK REFERENCE
Unit Core Content Covered
Unit 1 — Concepts Program definition; program structure (header,
declarations, body); variables/constants; all data types;
looping structures (for, while, do-while); control structures
(if-else, switch, ternary); syntax rules; programming
paradigms (OOP, functional, imperative, declarative,
event-driven); OOP four pillars; development approaches
(Waterfall, Agile, Spiral).
Unit Core Content Covered
Unit 2 — Development Phases 5 phases: Planning (feasibility — technical, economic,
operational, schedule), Analysis & Design, Development,
Testing, Implementation. Changeover strategies (direct,
parallel, phased, pilot).
Unit 3 — Design & Analysis Program design vs analysis; DFD tools and levels;
pseudocode rules and full example; HIPO diagrams;
structure charts; design levels (architectural, high-level,
detailed); types of design (form, file organisation,
database/normalisation).
Unit 4A — C Language C structure; data types and sizes; printf/scanf I/O;
identifiers and reserved words; literals; conditional
statements; break/continue/goto; library functions (stdio,
math, string, stdlib); user-defined functions; arguments vs
parameters; pass by value vs reference.
Unit 4B — Java/OOP Java/JVM/bytecode; program structure; [Link];
Scanner input; primitive and reference types; operators;
boolean expressions; for/while/do-while/for-each loops;
class anatomy (attributes, constructor, methods,
getters/setters); objects; 1D and 2D arrays; exception
handling (try-catch-finally, common exception classes).
Unit 5 — Testing & Debugging Testing vs debugging; 7 testing types (smoke, functional,
usability, security, performance, regression, compliance);
4 testing levels (unit, integration, system, UAT); 5 testing
methods (black-box, white-box, grey-box, agile, ad-hoc);
test data categories (normal, boundary, erroneous); 4 bug
types; 6-step debugging process; 7 debugging techniques.
Unit 6 — Training & Maintenance Training needs analysis; 7 training methods; user manual
components; 4 maintenance types; maintenance
schedule; maintenance tools (Git, Jira, CI/CD, profilers);
performance monitoring metrics and tools; bug
rectification process; change management process.
— END OF STUDY NOTES —
IT/CU/ICT/CR/10/6 | Computer Programming | TVET CDACC | 300 Hours