2018 July Paper – Full Detailed Answers
Question 1
(a) Advantages of structured programming languages
1. Modularity: Programs are divided into modules/functions, making them
easier to manage.
2. Readability: Clear control structures (sequence, selection, iteration)
improve understanding.
3. Ease of debugging and testing: Errors can be isolated to specific
modules.
(b) Differentiate between low level and high level programming languages
Low-level languages (e.g., Assembly, Machine code):
o Close to hardware
o Difficult to write and maintain
o Not portable
o High efficiency
High-level languages (e.g., C, Pascal):
o Close to human language
o Easier to write and maintain
o Portable
o Require compilation/interpretation
(c) (i) Flowchart for trip schedule
text
[Start] → [Input day number] → [Check day]
↓
Day=1 → [Output "Tsavo"]
Day=2 → [Output "Mara"]
Day=3 → [Output "EPZ"]
Day=4 → [Output "CocaCola Plant"]
Else → [Output "Not applicable"]
↓
[Stop]
(ii) C program using switch statement
c
#include<stdio.h>
int main() {
int day;
printf("Enter day number (1-4): ");
scanf("%d", &day);
switch(day) {
case 1: printf("Destination: Tsavo\n"); break;
case 2: printf("Destination: Mara\n"); break;
case 3: printf("Destination: EPZ\n"); break;
case 4: printf("Destination: CocaCola Plant\n"); break;
default: printf("Not applicable\n");
}
return 0;
}
Question 2
(a) Explain in C programming:
(i) Sentinel: A special value used to indicate the end of data entry in
loops (e.g., -1 for positive numbers).
(ii) Break: A control statement used to exit a loop or switch statement
immediately.
(b) Two disadvantages of monolithic programming
1. Difficult to debug: Large single block of code makes error location hard.
2. Poor reusability: Code cannot be easily reused in other programs.
(c) Distinguish between source code and object code
Source code: Human-readable program written in high-level language
(e.g., .c, .pas files).
Object code: Machine-readable code produced by compiler (.obj files),
not yet linked.
(d) C program for triangle area
c
#include<stdio.h>
#include<math.h>
int main() {
float a, b, c, S, area;
printf("Enter three sides of triangle: ");
scanf("%f %f %f", &a, &b, &c);
S = (a + b + c) / 2;
area = sqrt(S * (S - a) * (S - b) * (S - c));
printf("Area = %.3f\n", area);
return 0;
}
Question 3
(a) Four qualities of a good algorithm
1. Finiteness: Must terminate after finite steps.
2. Definiteness: Each step is clear and unambiguous.
3. Input: Zero or more inputs.
4. Output: At least one output.
(b) Role of header files
stdio.h: Contains standard input/output functions (printf, scanf).
math.h: Contains mathematical functions (sqrt, pow).
(c) Appropriate use of Pascal keywords
goto: Rarely used; only for emergency jumps out of deeply nested loops.
type: Used to define custom data types for better data organization.
(d) C program for athlete awards
c
#include<stdio.h>
int calculateAward(int rank) {
if(rank == 1) return 1000000;
else if(rank == 2) return 500000;
else if(rank == 3) return 250000;
else return 0;
}
int main() {
int rank;
printf("Enter rank: ");
scanf("%d", &rank);
printf("Award: Ksh %d\n", calculateAward(rank));
return 0;
}
Question 4
(a) (i) Two ways of checking program correctness
1. Dry run: Manually tracing through code with sample data.
2. Walkthrough: Team review of code logic.
(ii) Two categories of test data
1. Normal data: Valid inputs within expected range.
2. Abnormal data: Invalid inputs to test error handling.
(b) Parameter passing circumstances
Pass by value: When original value should not be modified.
Pass by reference: When function needs to modify original variable.
(c) Technical vs. user documentation
Technical: For programmers; includes algorithms, flowcharts, code
comments.
User: For end-users; includes how to use the program, input formats.
(d) Pascal program with procedure
pascal
program SquareProcedure;
var num: integer;
procedure computeSquare(n: integer);
begin
writeln('Number: ', n, ' Square: ', n * n);
end;
begin
write('Enter a positive integer: ');
readln(num);
computeSquare(num);
end.
Question 5
(a) (i) Queue operations
1. Enqueue: Add element to rear.
2. Dequeue: Remove element from front.
(ii) Linked list description
A dynamic data structure where each node contains data and a pointer to the
next node.
(b) (i) File handling modes
a: Append mode (adds to end of file).
w: Write mode (overwrites file).
r: Read mode (opens for reading).
(ii) x++ vs ++x
x++: Post-increment; returns original value, then increments.
++x: Pre-increment; increments first, then returns new value.
(c) (i) Steps for swapping in array
1. Store first element in temporary variable: temp = a[i]
2. Assign second element to first: a[i] = a[j]
3. Assign temp to second: a[j] = temp
(ii) Selection sort on 8,4,6,12,3,2,5
Pass 1: 2,4,6,12,3,8,5
Pass 2: 2,3,6,12,4,8,5
Pass 3: 2,3,4,12,6,8,5
Pass 4: 2,3,4,5,6,8,12
Pass 5: 2,3,4,5,6,8,12
Pass 6: 2,3,4,5,6,8,12
Sorted: 2,3,4,5,6,8,12
Question 6
(a) Four characteristics of reusable programs
1. Modularity: Divided into independent modules.
2. Well-documented: Clear comments and documentation.
3. Parameterized: Uses parameters for flexibility.
4. Generic: Works with different data types.
(b) (i) Random access
Direct access to any record in a file without reading preceding records.
(ii) gets() vs puts()
gets(): Reads a string from standard input.
puts(): Writes a string to standard output.
(c) Trace table
text
Line | x | y | z
-----|----|----|----
Init | 3 | 9 | -5
3 | 3 | 9 | -5
4 | 3 | 9 | -5
5 | 3 | 9 | -5 (ternary ignored)
6 | 3 | 9 | 3 (3 % 9 = 3)
Final: x=3, y=9, z=3
(d) Pascal file reading program
pascal
program ReadStudents;
var f: text; line: string;
begin
assign(f, 'D:\[Link]');
reset(f);
while not eof(f) do begin
readln(f, line);
writeln(line);
end;
close(f);
end.
Question 7
(a) In-built function
Predefined function provided by language library (e.g., sqrt(), strlen()).
(b) Record vs. array
Record: Holds heterogeneous data (different types) under one name.
Array: Holds homogeneous data (same type) in indexed locations.
(c) (i) Sequential search algorithm
Check each element from start to end until target is found or list ends.
(ii) Binary search for 45
List: 12,15,18,20,25,30,48,50,75
Step 1: Middle=25, 45>25 → right half: 30,48,50,75
Step 2: Middle=48, 45<48 → left half: 30
Step 3: 45≠30 → not found
(d) Pascal program with while loop
pascal
program OddNumbers;
var i: integer;
begin
i := 1;
while i <= 29 do begin
writeln(i:2, ' ', i*i:4);
i := i + 2;
end;
end.
Question 8
(a) C escape characters
\n: Newline
\t: Horizontal tab
(b) (i) Structure declaration format
c
struct struct_name {
data_type1 member1;
data_type2 member2;
// ... more members
};
(ii) Reasons for using functions
1. Code reusability: Write once, use many times.
2. Modularity: Break complex problems into smaller parts.
(c) Repeat until flowchart
text
[Start]
↓
[Execute body]
↓
[Condition] → False → [Body]
↓
True
↓
[Stop]
(d) Pascal pattern program
pascal
program PatternOutput;
var i, j: integer;
begin
for i := 1 to 4 do begin
for j := 1 to 4 do
write(i, ' ');
writeln;
end;
end.
📗 2019 July Paper – Full Detailed Answers
Question 1
(a) (i) Two advantages of assembly language
1. Hardware control: Direct access to processor and memory.
2. Efficiency: Produces highly optimized machine code.
(ii) Procedural vs. non-procedural languages
Procedural: Uses procedures/functions to structure code (e.g., C, Pascal).
Non-procedural: Declarative; specifies what to do, not how (e.g., SQL).
(b) Reasons for top-down design
1. Simplifies complexity: Breaks problem into manageable modules.
2. Easier testing: Modules can be tested independently.
(c) Pascal expression evaluation
Given: a=4, b=6, c=10, d=3
Y = sqr(a) + b * c mod 4 / d
= sqr(4) + 6 * 10 mod 4 / 3
= 16 + 60 mod 4 / 3
= 16 + 0 / 3 (60 mod 4 = 0)
= 16 + 0
= 16
(d) Hostel allocation flowchart
text
[Start] → [Register for term] → [Pay fees] → [Apply for hostel]
↓
[Check criteria] → Met → [Allocate room] → [Stop]
↓
Not met → [No allocation] → [Stop]
Question 2
(a) (i) User-defined data type
A data type created by programmer using existing types (e.g., records in Pascal,
structures in C).
(ii) Patient details program
(I) Most appropriate: Record structure
(II) Pascal declaration:
pascal
type
Patient = record
PatientNo: integer;
Patient_Name: string;
Gender: char;
Age: integer;
end;
(b) (i) Stack operations
1. Push (add to top)
2. Pop (remove from top)
3. Peek (view top without removing)
(ii) Queue vs. linked list
Queue: FIFO structure; elements added at rear, removed from front.
Linked list: Linear collection of nodes; can insert/delete anywhere.
(c) C program for grading
c
#include<stdio.h>
int main() {
int points;
printf("Enter points (1-4): ");
scanf("%d", &points);
switch(points) {
case 1: printf("Grade: Distinction\n"); break;
case 2: printf("Grade: Credit\n"); break;
case 3: printf("Grade: Pass\n"); break;
case 4: printf("Grade: Fail\n"); break;
default: printf("Invalid points\n");
}
return 0;
}
Question 3
(a) (i) Two characteristics of algorithm
1. Input: Receives zero or more inputs.
2. Output: Produces at least one output.
(ii) Quick sort algorithm
text
1. Choose pivot element
2. Partition array: elements < pivot to left, > pivot to right
3. Recursively sort left and right partitions
(b) C program for prime number
c
#include<stdio.h>
int main() {
int n, i, flag = 1;
printf("Enter integer: ");
scanf("%d", &n);
if(n <= 1) flag = 0;
for(i = 2; i <= n/2; i++) {
if(n % i == 0) {
flag = 0;
break;
}
}
if(flag) printf("%d is prime\n", n);
else printf("%d is not prime\n", n);
return 0;
}
(c) Pascal program for sum
pascal
program SumIntegers;
var n, i, sum: integer;
begin
write('Enter positive integer: ');
readln(n);
sum := 0;
for i := 0 to n do
sum := sum + i;
writeln('Sum = ', sum);
end.
Question 4
(a) Two utility programs in translation
1. Linker: Combines object files into executable.
2. Loader: Loads executable into memory.
(b) (i) Three file organization techniques
1. Sequential: Records accessed in stored order.
2. Random/Direct: Direct access using key.
3. Indexed: Uses index for faster access.
(ii) Program interpretation
c
#include <stdio.h>
int main () {
int Myarray[4] = {10,20,30,40}; // Declare array
int j; // Loop variable
for (j = 3; j >= 0; j--) { // Loop backwards
printf("Element[%d] = %d\n", j, Myarray[j]); // Print
}
return 0;
}
Output:
Element[3] = 40
Element[2] = 30
Element[1] = 20
Element[0] = 10
(c) (i) Comment in Pascal
Text within { } or (* *) ignored by compiler; used for documentation.
(ii) Pascal program for uncovered area
pascal
program UncoveredArea;
var roomLength, roomWidth, carpetRadius, roomArea, carpetArea, uncovered:
real;
begin
write('Enter room length, width: ');
readln(roomLength, roomWidth);
write('Enter carpet radius: ');
readln(carpetRadius);
roomArea := roomLength * roomWidth;
carpetArea := 3.142 * carpetRadius * carpetRadius;
uncovered := roomArea - carpetArea;
writeln('Uncovered area = ', uncovered:0:2);
end.
Question 5
(a) (i) Module in programming
Self-contained unit of code performing specific task; promotes modularity.
(ii) Function vs. procedure in Pascal
Function: Returns a value.
Procedure: Does not return value.
(b) Bubble sort pseudocode
text
for i = 0 to n-2
for j = 0 to n-i-2
if array[j] > array[j+1]
swap array[j] and array[j+1]
(c) C file functions
putc(): Writes character to file.
fprintf(): Writes formatted data to file.
(d) C pattern program
c
#include<stdio.h>
int main() {
int i, j;
for(i = 4; i <= 6; i++) {
for(j = 4; j <= i; j++)
printf("%d ", j);
printf("\n");
}
return 0;
}
Question 6
(a) Reasons for data structures
1. Efficient data organization.
2. Easy data manipulation.
(b) (i) Program documents
1. Technical specification.
2. User manual.
(ii) writeln() vs write()
writeln(): Writes output and moves to new line.
write(): Writes output without moving to new line.
(c) Binary tree construction
text
Peter
/ \
George Tom
/ \ / \
Beatrice Wayne Joan Ray
Ray is at level 3.
(d) Pascal login program
pascal
program LoginSystem;
var code: string; attempts: integer;
begin
attempts := 0;
repeat
write('Enter code: ');
readln(code);
attempts := attempts + 1;
if code = '1234' then begin
writeln('Welcome');
break;
end else begin
writeln('The code is incorrect');
end;
until attempts = 3;
if attempts = 3 then writeln('Maximum attempts reached');
end.
Question 7
(a) Reserved words
break: Exits loop immediately.
continue: Skips to next iteration of loop.
(b) realloc vs. free
realloc(): Changes size of allocated memory block.
free(): Deallocates memory block.
(c) (i) Advantages of merge sort
1. Stable (preserves order of equal elements).
2. Good for large datasets.
(ii) Data structure
Linear array/list.
(d) Pascal 2x2 array program
pascal
program TwoByTwoArray;
var arr: array[1..2, 1..2] of integer; i, j: integer;
begin
for i := 1 to 2 do
for j := 1 to 2 do begin
write('Enter value [', i, ',', j, ']: ');
readln(arr[i, j]);
end;
writeln('Array entered successfully');
end.
Question 8
(a) (i) Making programs understandable
1. Meaningful variable names.
2. Proper indentation.
(ii) Escape sequence for table
\t for tab spacing.
(b) Escape sequences
\a: Alert/bell
\b: Backspace
\l: Not standard (likely \n)
\0: Null character
(c) (i) Stack errors
1. Underflow: Pop from empty stack.
2. Overflow: Push to full stack.
(ii) Error trapping in C
1. feof(): Checks end of file.
2. ferror(): Checks file error.
(d) Pascal bursary program
pascal
program BursaryAllocation;
var status: string;
begin
write('Enter student status: ');
readln(status);
if status = 'Orphan' then writeln('Amount: 15,000')
else if status = 'Needy' then writeln('Amount: 13,000')
else if status = 'Affirmative Action' then writeln('Amount: 13,000')
else writeln('Amount: 0');
end.
📙 2021 July Paper – Full Detailed Answers
Question 1
(a) (i) Programming language
Assembly language.
(ii) Two advantages
1. Direct hardware access.
2. High execution speed.
(b) Local vs. global variables
Local: Declared inside function; accessible only within that function.
Global: Declared outside functions; accessible throughout program.
(c) Pascal product program
pascal
program Product;
var a, b: integer;
begin
a := 20;
b := 40;
writeln('Product = ', a * b);
end.
(d) (i) Pascal record declaration
pascal
type
Student = record
name: string;
age: integer;
address: string;
end;
(ii) C file writing program
c
#include<stdio.h>
int main() {
FILE *fp;
char name[50];
int age;
fp = fopen("[Link]", "w");
printf("Enter name: ");
scanf("%s", name);
printf("Enter age: ");
scanf("%d", &age);
fprintf(fp, "Name: %s\nAge: %d", name, age);
fclose(fp);
return 0;
}
2021 July Paper – Full Detailed Answers
(Continued)
Question 2
(a) Output of C statements (x=60)
(i) x != -2 → 60 != -2 → 1 (true)
(ii) x^0 = 3 → This is invalid syntax (likely typo). If x ^ 0 meant XOR: 60 ^
0 = 60
(b) rewind() vs getw()
rewind(): Sets file position to beginning.
getw(): Reads integer from file.
(c) Pascal vowel checker
pascal
program VowelCheck;
var ch: char;
begin
write('Enter a character: ');
readln(ch);
case ch of
'a','A','e','E','i','I','o','O','u','U':
writeln(ch, ' is a vowel');
else writeln(ch, ' is not a vowel');
end;
end.
(d) (i) Loop control statements
1. break: Exits loop immediately.
2. continue: Skips to next iteration.
(ii) C even numbers program
c
#include<stdio.h>
int main() {
int n, i;
printf("Enter number: ");
scanf("%d", &n);
for(i = 2; i <= n; i += 2)
printf("%d ", i);
return 0;
}
Question 3
(a) Four sorting techniques
1. Bubble sort
2. Selection sort
3. Insertion sort
4. Quick sort
(b) (i) Purpose of writeln
Writes output and moves to new line.
(ii) Pascal interest program
pascal
program SimpleInterest;
var amount, period: real;
procedure calcInterest(a, p: real);
var interest: real;
begin
interest := a * p * 0.14;
writeln('Interest = ', interest:0:2);
end;
begin
write('Enter amount borrowed: ');
readln(amount);
write('Enter period (years): ');
readln(period);
calcInterest(amount, period);
end.
(c) Call by reference vs call by value
Call by value: Copies actual parameter value; changes don't affect
original.
Call by reference: Passes address; changes affect original
variable.
(d) Pascal program interpretation
pascal
Program alpha(input, output);
Var
x: char;
y: integer;
Procedure beta(var x: char; var y: integer);
Begin
y := ORD(x); // Converts char to ASCII
End;
Begin
x := 'A';
Beta(x, y); // Calls procedure
Writeln('ASCII code for ', x, ' is ', y); // Output: ASCII code for A
is 65
End.
Question 4
(a) (i) Reasons for documentation
1. Maintenance guidance
2. User reference
3. Future modifications
(ii) Pascal enumerated functions
1. ORD(): Returns ordinal value.
2. PRED(): Returns predecessor.
3. SUCC(): Returns successor.
(b) C operators purpose
&&: Logical AND
||: Logical OR
!=: Not equal
(c) C factors program
c
#include<stdio.h>
int main() {
int n, i;
printf("Enter positive integer: ");
scanf("%d", &n);
printf("Factors: ");
for(i = 1; i <= n; i++)
if(n % i == 0) printf("%d ", i);
return 0;
}
(d) Pascal pattern program
pascal
program Pattern;
var i, j: integer;
begin
for i := 1 to 5 do begin
for j := 1 to i do
write('$');
writeln;
end;
end.
Question 5
(a) r+ vs w+
r+: Opens for reading and writing; file must exist.
w+: Opens for reading and writing; creates new or truncates
existing.
(b) File organization techniques
1. Sequential: Records in order.
2. Random/Direct: Direct access via key.
(c) Pascal square root program
pascal
program SquareRoot;
var num: real;
begin
write('Enter number: ');
readln(num);
if num >= 0 then
writeln('Square root = ', sqrt(num):0:2)
else
writeln('Invalid: negative number');
end.
(d) Binary tree
(i) Construction (6,2,5,1,7,4,3)
text
6
/ \
2 7
/ \
1 5
/
4
/
3
(ii) Pre-order traversal
6, 2, 1, 5, 4, 3, 7
Question 6
(a) (i) Stack operations
1. Push
2. Pop
(ii) Packed array purpose
Saves memory by packing multiple elements into single memory unit.
(b) (i) Language selection factors
1. Problem type
2. Performance needs
3. Developer expertise
4. Platform requirements
(ii) Programming approaches
Monolithic: Single block of code; hard to maintain.
Visual: Uses graphical elements; drag-and-drop.
(c) Bubble vs selection sort
Bubble sort: Repeatedly swaps adjacent elements.
Selection sort: Selects smallest element and places in position.
(d) C queue deletion code
c
if(front == -1) {
printf("Queue empty");
} else {
deleted = queue[front];
if(front == rear) front = rear = -1;
else front++;
}
Question 7
(a) Compiler benefits
1. Error detection before execution.
2. Optimized code generation.
(b) Constant naming factors
1. Meaningful names
2. UPPERCASE convention
3. No reserved words
4. Descriptive
(c) Pascal sum function
pascal
program SumFunction;
var a, b: integer;
function add(x, y: integer): integer;
begin
add := x + y;
end;
begin
write('Enter two numbers: ');
readln(a, b);
writeln('Sum = ', add(a, b));
end.
(d) C linear search program
c
#include<stdio.h>
int main() {
int arr[] = {45,34,65,30,25,56};
int i, found = 0;
for(i = 0; i < 6; i++) {
if(arr[i] == 30) {
printf("30 found at index %d\n", i);
found = 1;
break;
}
}
if(!found) printf("30 not found\n");
return 0;
}
Question 8
(a) Six C conversion specifiers
1. %d - integer
2. %f - float
3. %c - character
4. %s - string
5. %x - hexadecimal
6. %o - octal
(b) (i) Importance of subprograms
1. Code reuse
2. Modularity
(ii) Documentation elements
1. Table of contents
2. Index
3. Version history
4. Appendices
(c) Rectangle area flowchart
text
[Start] → [Declare constants: L=70, W=130] → [area = L*W] → [Output area] →
[Stop]
(d) C largest of three numbers
c
#include<stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if(a >= b && a >= c) printf("Largest: %d", a);
else if(b >= a && b >= c) printf("Largest: %d", b);
else printf("Largest: %d", c);
return 0;
}
📓 2021 November Paper – Full Detailed Answers
Question 1
(a) (i) Variable type
Enumerated type.
(ii) ASCII value statement
pascal
writeln(ORD('D'));
(b) Source vs object code
Source: Human-readable (.pas, .c files).
Object: Machine-readable (.obj files) after compilation.
(c) Pascal pattern program
pascal
program Pattern;
var i, j: integer;
begin
for i := 1 to 5 do begin
for j := 1 to i do
write('&');
writeln('''');
end;
end.
(d) (i) Employee record
pascal
type
Employee = record
name: string;
hours: array[1..5] of real;
address: string;
end;
(ii) C data file program
c
#include<stdio.h>
int main() {
FILE *fp;
int empNo;
float basicPay;
fp = fopen("[Link]", "wb");
printf("Enter employee number: ");
scanf("%d", &empNo);
printf("Enter basic pay: ");
scanf("%f", &basicPay);
fwrite(&empNo, sizeof(int), 1, fp);
fwrite(&basicPay, sizeof(float), 1, fp);
fclose(fp);
return 0;
}
Question 2
(a) Operator precedence
1. *, /, mod (left to right)
2. +, - (left to right)
3. >, <, >=, <=
4. ==, !=
5. &&
6. ||
7. =
(b) Pseudocode vs structure narratives
Pseudocode: Structured English-like algorithm representation.
Structure narratives: Plain English description.
(c) C reverse array program
c
#include<stdio.h>
int main() {
int arr[10], i;
printf("Enter 10 numbers: ");
for(i = 0; i < 10; i++)
scanf("%d", &arr[i]);
printf("Reverse order: ");
for(i = 9; i >= 0; i--)
printf("%d ", arr[i]);
return 0;
}
(d) (i) Compiler functions
1. Translates source to object code.
2. Checks syntax errors.
(ii) Pascal cost program
pascal
program ItemCost;
var price, cost: real; quantity: integer;
begin
repeat
write('Enter price (10-100): ');
readln(price);
until (price >= 10) and (price <= 100);
repeat
write('Enter quantity (1-20): ');
readln(quantity);
until (quantity >= 1) and (quantity <= 20);
cost := price * quantity;
writeln('Total cost = ', cost:0:2);
end.
Question 3
(a) Documentation contents
(i) Program documentation
1. Algorithms
2. Flowcharts
3. Code comments
(ii) User documentation
1. Installation guide
2. User manual
3. Troubleshooting
(b) (i) Readability improvement
1. Proper indentation
2. Meaningful variable names
(ii) Division flowchart
text
[Start] → [Input num1, num2] → [num2=0?] → Yes → [Print "Error!"] → [Stop]
↓ No
[result = num1/num2] → [Print result] → [Stop]
(c) do...while vs while
do...while: Executes at least once; condition checked after loop.
while: May not execute; condition checked before loop.
(d) C program interpretation
c
main() {
int i,j;
i=12; j=10;
fn(&i,&j); // Calls function with addresses
printf("%d %d\n", i,j); // Output: 13 11
}
fn(m,n);
int*m,*n; {
(*m)++; // Increments value at address m
(*n)++; // Increments value at address n
printf("%d,%d",*m,*n); // Output: 13,11
}
Question 4
(a) (i) Documentation creation reasons
1. Maintenance reference
2. User guidance
3. Knowledge transfer
(ii) Post-compilation errors
1. Runtime errors
2. Logical errors
(b) Pascal equality checker
pascal
program EqualityCheck;
var a, b: integer; equal: boolean;
begin
write('Enter two integers: ');
readln(a, b);
equal := (a = b);
writeln('Are they equal? ', equal);
end.
(c) Sequential search algorithm
text
1. Start from first element
2. Compare with target
3. If match, return position
4. Else move to next
5. Repeat until found or end
(d) C discount program
c
#include<stdio.h>
int main() {
char customerType;
float amount;
printf("Enter customer type (T=Table, W=Walk-in): ");
scanf("%c", &customerType);
printf("Enter sales amount: ");
scanf("%f", &amount);
if(customerType == 'T') {
if(amount >= 1000) printf("Discount: 10%%\n");
else printf("Discount: 5%%\n");
} else {
printf("No discount\n");
}
return 0;
}
Question 5
(a) Quick sort characteristics
1. Divide and conquer
2. Average O(n log n)
3. Unstable sort
4. In-place
(b) File reading error causes
1. File not found
2. Insufficient permissions
3. Corrupted file
(c) Pascal square root program
pascal
program DigitSqrt;
var digit: integer;
begin
write('Enter digit (0-9): ');
readln(digit);
if(digit >= 0) and (digit <= 9) then
writeln('Square root = ', sqrt(digit):0:3)
else
writeln('Invalid digit');
end.
(d) Quadratic equation flowchart
text
[Start] → [Input a,b,c] → [discriminant = b²-4ac] → [disc<0?] → Yes →
[Complex roots] → [Stop]
↓ No
[Root1 = (-b+√disc)/2a] → [Root2 = (-b-√disc)/2a] → [Output roots] → [Stop]
Question 6
(a) (i) Non-linear data structures
1. Trees
2. Graphs
(ii) Compilation activities
1. Lexical analysis
2. Syntax analysis
3. Code generation
(b) (i) Binary search tree
text
15
/ \
9 22
/ \ / \
5 11 24 29
/ \ /
3 6 30
\
10
\
14
(ii) Post-order traversal
3, 10, 14, 6, 5, 11, 9, 30, 24, 29, 22, 15
(c) Dry run vs walkthrough
Dry run: Manual tracing with sample data.
Walkthrough: Team review meeting.
(d) Pascal cube volume
pascal
program CubeVolume;
var length, volume: real;
function calcVolume(L: real): real;
begin
calcVolume := L * L * L;
end;
begin
write('Enter cube length: ');
readln(length);
volume := calcVolume(length);
writeln('Volume = ', volume:0:2);
end.
Question 7
(a) (i) Test data
Data used to verify program correctness.
(ii) Bug
Error or flaw in program causing incorrect behavior.
(b) (i) Programming project sources
1. Client requests
2. Personal needs
3. Academic assignments
(ii) Pseudocode use circumstances
1. Algorithm design
2. Program planning
3. Communication
(c) Evaluation (j=i+1+6)
Given: i=6, j=10
(i) Prefix increment: ++i + 1 + 6 → 7 + 1 + 6 = 14
(ii) Postfix decrement: j-- + 1 + 6 → 10 + 1 + 6 = 17 (j becomes 9 after)
(d) Pascal temperature program
pascal
program Temperature;
var temps: array[1..4, 1..3] of real; i, j: integer;
begin
for i := 1 to 4 do begin
writeln('Location ', i, ':');
for j := 1 to 3 do begin
write(' Time ', j, ': ');
readln(temps[i, j]);
end;
end;
// Output
for i := 1 to 4 do begin
write('Location ', i, ': ');
for j := 1 to 3 do
write(temps[i, j]:0:1, ' ');
writeln;
end;
end.
Question 8
(a) (i) Structured languages examples
1. Java
2. Python
3. FORTRAN
4. COBOL
(ii) High-level language advantages
1. Easy to learn
2. Portable
(b) Queue insertion flowchart
text
[Start] → [Is queue full?] → Yes → [Overflow error] → [Stop]
↓ No
[rear = rear+1] → [queue[rear] = element] → [Stop]
(c) Pascal division program
pascal
program Division;
var a, b: integer; quotient, remainder: integer;
begin
a := 16; b := 3;
quotient := a div b;
remainder := a mod b;
writeln('Quotient = ', quotient);
writeln('Remainder = ', remainder);
end.
(d) C adult checker
c
#include<stdio.h>
int main() {
int age;
printf("Enter age: ");
scanf("%d", &age);
printf("Age: %d\n", age);
if(age > 18) printf("You are an adult\n");
return 0;
}
📒 2022 July Paper – Full Detailed Answers
Question 1
(a) (i) High-level language advantages
1. Easy to learn and use
2. Portable across platforms
3. Rich libraries
4. Good for large projects
(ii) Bug definition
Error in program causing unexpected behavior.
(b) Function call vs definition
Call: Using function by name with arguments.
Definition: Actual implementation of function.
(c) Boolean expression evaluation
(7%2) * 3 + 4 < 5
= (1) * 3 + 4 < 5
=3 + 4 < 5
=7 < 5
= 0 (false)
(d) Student grading flowchart
text
[Start] → [Input performance, attendance] → [performance>50?] → No →
[Supplementary] → [Stop]
↓ Yes
[attendance>75?] → Yes → [Pass] → [Stop]
↓ No
[Retake course] → [Stop]
Question 2
(a) (i) Pascal comment symbols
1. { ... }
2. (* ... *)
(ii) Purpose of statements
goto: Unconditional jump to label (avoided in structured
programming).
continue: Skips to next iteration in loop.
(b) Global variable errors
1. Unintended modification
2. Name conflicts
3. Difficult debugging
(c) Pascal data bundles program
pascal
program DataBundles;
var amount, bundles: real;
begin
write('Enter amount (Ksh): ');
readln(amount);
bundles := amount * 5; // 1 Ksh = 5MB
writeln('Bundles purchased: ', bundles:0:2, ' MB');
end.
(d) C program interpretation
c
#include<stdio.h>
main() {
int i, sum =0; // Declare variables
int num[6] = {30,40,60,10,25,38}; // Initialize array
for(i=0; i<6; i++) { // Loop through array
sum=sum +num[i]; // Add each element to sum
if(i==3) break; // Stop when i=3 (after 4 elements)
}
printf("%d", sum); // Output: 140 (30+40+60+10)
}
Question 3
(a) (i) Modular design
Dividing program into independent, manageable modules.
(ii) Pointer importance
1. Dynamic memory allocation
2. Efficient array handling
3. Function parameter passing
(b) Sequence vs iteration
Sequence: Statements executed in order.
Iteration: Statements repeated based on condition.
(c) Decision table
text
Conditions | R1 | R2 | R3 | R4
-----------------------------|----|----|----|----
Academic qualification = Y | Y | N | N | -
Experience >= 5 years = Y | N | Y | N | -
Discipline = Y | - | - | Y | N
-----------------------------|----|----|----|----
Action: Offer position | X | X | X | -
(d) Pascal case program
pascal
program CompetencyTest;
var outcome: char;
begin
write('Enter outcome (E,M,A,B): ');
readln(outcome);
case outcome of
'E','e': writeln('Exceed Expectation');
'M','m': writeln('Met Expectation');
'A','a': writeln('Approaching Expectation');
'B','b': writeln('Below Expectation');
else writeln('Enter a valid outcome');
end;
end.
Question 4
(a) (i) Monolithic programming disadvantages
1. Hard to debug
2. Poor maintainability
3. No code reuse
4. Difficult teamwork
(ii) Program documentations
1. Technical documentation
2. User manual
(b) Doubly linked list diagram
text
[NULL]←[Prev|Data|Next]↔[Prev|Data|Next]↔[Prev|Data|Next]→[NULL]
(c) Corrected Pascal program
pascal
program StudAge(input, output);
var Age: integer;
begin
writeln('Enter the age');
readln(Age);
if (Age >= 18) then
writeln('Admit')
else
writeln('Dismiss');
end.
(d) Pascal reverse array
pascal
program ReverseArray;
var arr: array[1..5] of integer; i: integer;
begin
writeln('Enter 5 numbers:');
for i := 1 to 5 do
readln(arr[i]);
writeln('Reverse order:');
for i := 5 downto 1 do
write(arr[i], ' ');
end.
Question 5
(a) (i) Program development stages
1. Problem definition
2. Analysis
3. Design
4. Coding
5. Testing
6. Maintenance
(ii) Terms explanation
Dry run: Manual code execution with sample data.
Compilation: Translating source to machine code.
(b) Fixed vs dynamic data structures
Fixed: Size determined at compile time (arrays).
Dynamic: Size changes at runtime (linked lists).
(c) Pascal functions
1. concat() - join strings
2. ord() - char to ASCII
3. length() - count characters
4. pred() - previous in enum
(d) C structure declaration
c
struct Student {
char name[50];
char dob[11]; // DD/MM/YYYY
float height;
float weight;
char subcounty[30];
};
Question 6
(a) Program documentation items
1. Table of contents
2. Index
3. Version history
4. Appendices
(b) Event-driven vs OOP
Event-driven: Responds to events (clicks, keypress).
OOP: Organizes around objects with properties/methods.
(c) Selection sort passes
Array: 69,80,78,42,30,56,48,62
Pass 1: 30,80,78,42,69,56,48,62
Pass 2: 30,42,78,80,69,56,48,62
Pass 3: 30,42,48,80,69,56,78,62
Pass 4: 30,42,48,56,69,80,78,62
Pass 5: 30,42,48,56,62,80,78,69
Pass 6: 30,42,48,56,62,69,78,80
Pass 7: 30,42,48,56,62,69,78,80
(d) C compound operator program
c
#include<stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
(a > b) ? printf("%d is larger", a) : printf("%d is larger", b);
return 0;
}
Question 7
(a) (i) C escape sequences
1. \n - newline
2. \t - tab
3. \\ - backslash
4. \" - double quote
(ii) Portability
Ability of program to run on different platforms without modification.
(b) Pascal file operations
1. eof() - detect end of file
2. reset() - open for reading
3. file of - binary file handle
(c) Binary search tree
(i) Construction (names sorted alphabetically)
text
Jane
/ \
Bethel Martin
/ \ / \
Arthur David Levi Zoe
(ii) Pre-order traversal
Jane, Bethel, Arthur, David, Martin, Levi, Zoe
(d) C memory address program
c
#include<stdio.h>
int main() {
char ch;
printf("Enter character: ");
scanf("%c", &ch);
printf("Character: %c\n", ch);
printf("Memory address: %p", (void*)&ch);
return 0;
}
Question 8
(a) (i) Binary search advantages
1. Efficient for large datasets
2. O(log n) time complexity
(ii) Pass by reference reasons
1. Modify original variables
2. Avoid copying large data
(b) Serial vs sequential files
Serial: Records in order of creation.
Sequential: Records in sorted order.
(c) C square root program
c
#include<stdio.h>
#include<math.h>
int main() {
double num;
printf("Enter number: ");
scanf("%lf", &num);
if(num >= 0)
printf("Square root = %.2f", sqrt(num));
else
printf("Invalid: negative number");
return 0;
}
(d) Pascal BMI program
pascal
program BMI;
var weight, height, bmi: real;
function calculateBMI(w, h: real): real;
begin
calculateBMI := w / (h * h);
end;
begin
write('Enter weight (kg): ');
readln(weight);
write('Enter height (m): ');
readln(height);
bmi := calculateBMI(weight, height);
write('BMI = ', bmi:0:1, ' - ');
if bmi < 18 then writeln('Underweight')
else if bmi <= 25 then writeln('Normal')
else writeln('Overweight');
end.