2920/103

STRUCTURED PROGRAMMING

July 2021

Time: 3 hours

 

THE KENYA NATIONAL EXAMINATIONS COUNCIL

DIPLOMA IN INFORMATION COMMUNICATION TECHNOLOGY

MODULE I

STRUCTURED PROGRAMMING

3 hours

 

INSTRUCTIONS TO THE CANDIDATES

 

1. This paper consists of EIGHT questions.

2. Answer any FIVE questions in the answer booklet provided.

3. Candidates should answer all questions in English.

4. This paper consists of 4 printed pages.

5. Candidates should check the question paper to ascertain that all the pages are printed as indicated and that no questions are missing.

 

 

Question 1

 

(a) Study the following program and then answer the questions that follow.

 

“`

INC COUNT

MOVE TOTAL 20

ADD A, B

“`

 

(i)Identify the programming language used in this program.

The programming language used is Assembly Language.

 

(ii)Outline two advantages of the language identified in (i).

1. Low-level control: Assembly language allows direct manipulation of hardware, providing fine-grained control over system resources.

2. Efficiency: Programs written in assembly language are highly optimized and execute faster compared to high-level languages.

 

(b)Distinguish between local and global variables as used in programming.

Local variables are declared within a function or block and can only be accessed within that scope. They are created when the function is called and destroyed when the function exits.

Global variables are declared outside all functions and can be accessed by any function within the program. They persist throughout the program’s execution.

 

(c)Write a program in Pascal language that computes and displays the product of two assigned values 20 and 40.**

“`pascal

program ProductCalculator;

var

a, b, product: integer;

begin

a := 20;

b := 40;

product := a * b;

writeln(‘The product is: ‘, product);

end.

“`

 

(d)

(i)A college intends to store the following student’s details in a computer: name, age, and address. Declare a Pascal language record that would store these details.**

“`pascal

type

Student = record

name: string;

age: integer;

address: string;

end;

“`

 

(ii)Write a program in C language that prompts a user to enter a student’s name and age. The program then writes the name and age into a text file.

“`c

#include <stdio.h>

int main() {

char name[50];

int age;

FILE *file;

 

printf(“Enter student’s name: “);

scanf(“%s”, name);

printf(“Enter student’s age: “);

scanf(“%d”, &age);

 

file = fopen(“student.txt”, “w”);

if (file == NULL) {

printf(“Error opening file!”);

return 1;

}

fprintf(file, “Name: %s\nAge: %d”, name, age);

fclose(file);

return 0;

}

“`

 

 

Question 2

 

2. (a) The following are program statements in C language. Use them to answer the question that follows: ✔ (2 marks)

Given the statements:

(i) x != 2;

(ii) x % = 3;

Given that the value of x = 60, state the output generated when each of the statements is executed.

Correct Answers:

(i) x != 2; → This is a comparison operation. Since 60 is not equal to 2, the condition evaluates to true (1).

(ii) x % = 3; → This statement is incorrect syntax in C. The correct form should be:

x = x % 3;

 

When executed with x = 60:

60 % 3 = 0

So, the output is 0.

 

2. (b) Differentiate between rewind() and getw() as used in C programming. ✔ (4 marks)

Correct Answer:

rewind():

This function sets the file position indicator to the beginning of the specified file.

Syntax: rewind(FILE *stream);

getw():

This function reads an integer value from a file.

Syntax: int getw(FILE *stream);

 

 

2. (c) Write a program in Pascal language that prompts a user to enter a character. The program then determines whether the character input is a vowel or not and displays an appropriate message. Use case statement. ✔ (5 marks)

Correct Answer (Pascal Program):

 

program VowelCheck;

uses crt;

var

ch: char;

begin

clrscr;

writeln(‘Enter a character: ‘);

readln(ch);

 

case ch of

‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’:

writeln(‘The character is a vowel.’);

else

writeln(‘The character is not a vowel.’);

end;

 

readln;

end.

 

 

 

(d)

(i)Explain two statements used to change the flow of execution in a C program loop.**

1. break: This statement terminates the loop immediately and transfers control to the statement following the loop.

2. continue: This statement skips the remaining code in the current iteration of the loop and proceeds to the next iteration.

 

(ii)Write a program in C language that displays even numbers up to a given number input.

“`

#include <stdio.h>

int main() {

int n, i;

printf(“Enter a number: “);

scanf(“%d”, &n);

for (i = 1; i <= n; i++) {

if (i % 2 == 0) {

printf(“%d “, i);

}

}

return 0;

}

“`

 

 

Question 3

 

(a)State four sorting techniques used in programming.**

1. Bubble Sort

2. Selection Sort

3. Insertion Sort

4. Quick Sort

 

(b)

(i)Describe the purpose of `writeln;` statement as used in Pascal programming language.**

The `writeln;` statement is used to output data to the screen and move the cursor to the next line after printing.

 

(ii)Write a program in Pascal language that prompts a user to enter the amount of money borrowed and the repayment period. The program then passes these values to a procedure, computes and displays the simple interest at a rate of 14% per annum.**

“`pascal

program SimpleInterest;

var

amount, period: real;

 

procedure CalculateInterest(amt, time: real);

var

interest: real;

begin

interest := amt * time * 0.14;

writeln(‘Simple Interest: ‘, interest:0:2);

end;

 

begin

write(‘Enter amount borrowed: ‘);

readln(amount);

write(‘Enter repayment period (in years): ‘);

readln(period);

CalculateInterest(amount, period);

end.

“`

 

(c)Distinguish between call by reference and call by value as used in programming.**

Call by value: A copy of the actual parameter’s value is passed to the function. Changes made to the parameter inside the function do not affect the original value.

Call by reference: The address of the actual parameter is passed to the function. Changes made to the parameter inside the function affect the original value.

 

(d)The following Pascal program was created by a student during a practical lesson. Use it to answer the question that follows.**

 

“`pascal

Program alpha(input, output);

Var

x: char;

y: integer;

Procedure beta(var x: char; var y: integer);

Begin

y := ORD(x);

End;

Begin

x := ‘A’;

Beta(x, y);

Writeln(‘ASCII code for ‘, x, ‘ is ‘, y);

End.

“`

 

Interpret the program.

The program defines a procedure `beta` that takes a character `x` and an integer `y` as parameters. The procedure converts the character `x` to its ASCII value and assigns it to `y`. In the main program, the character `’A’` is passed to `beta`, which calculates its ASCII value (65) and prints it.

 

 

Question 4

 

(a)

(i)Outline three reasons for preparing program documentation.

1. Maintenance: Documentation helps developers understand and maintain the code.

2. Collaboration: It allows multiple developers to work on the same project efficiently.

3. Troubleshooting: Documentation aids in identifying and fixing errors in the program.

 

(ii)Explain two inbuilt Pascal functions used to manipulate an enumerated data type.**

1. Ord(): Returns the ordinal value of an enumerated type.

2. Pred(): Returns the predecessor of an enumerated value.

 

(b)Outline the purpose of each of the following operators in a C program:

(i)`&&`

Logical AND operator. It returns true if both operands are true.

(ii)`||`

Logical OR operator. It returns true if at least one operand is true.

(iii) `!=`

Not equal to operator. It returns true if the operands are not equal.

 

(c)Write a program in C language that prompts a user to enter a positive integer. The program then determines and outputs the factors of the integer.**

“`c

#include <stdio.h>

int main() {

int n, i;

printf(“Enter a positive integer: “);

scanf(“%d”, &n);

printf(“Factors of %d are: “, n);

for (i = 1; i <= n; i++) {

if (n % i == 0) {

printf(“%d “, i);

}

}

return 0;

}

“`

 

(d)Write a program in Pascal language that generates the following output when executed:**

“`

$$

$$

$$

“`

“`pascal

program Pattern;

var

i: integer;

begin

for i := 1 to 3 do

writeln(‘$$’);

end.

“`

 

 

### Question 5

 

(a)State the differences between `r+` and `w+` file commands as used in C programming.**

r+: Opens a file for both reading and writing. The file must exist.

w+: Opens a file for both reading and writing. If the file exists, it is truncated to zero length. If it does not exist, it is created.

 

(b)Describe two types of file organization techniques that could be adopted during program writing.

1. Sequential File Organization: Data is stored in a sequential manner, and records are accessed one after another.

2. Random Access File Organization: Data can be accessed directly using a key or index, allowing for faster retrieval.

 

(c)Write a Pascal program that prompts a user to read a number. The program checks to determine whether the number is a positive integer. The program then computes and outputs the square root of the number using a predefined function.

 

program SquareRoot;

var

num: real;

begin

write(‘Enter a number: ‘);

readln(num);

if num > 0 then

writeln(‘Square root: ‘, sqrt(num):0:2)

else

writeln(‘The number is not positive.’);

end.

“`

 

(d)Given the nodes: 6, 2, 5, 1, 7, 4, and 3:

(i)Construct a binary tree.

“`

6

/ \

2 7

/ \ \

1 5 4

/

3

“`

 

(ii)Write the output generated when the tree in (i) is traversed using pre-order traversal strategy.

Pre-order traversal: 6, 2, 1, 5, 3, 7, 4

 

 

Question 6

 

(a)

(i)Outline two operations that could be performed on a stack data structure.**

1. Push: Adds an element to the top of the stack.

2. Pop: Removes and returns the top element from the stack.

 

(ii)Explain the purpose of a packed array in Pascal programming.

A packed array in Pascal is used to store data more efficiently by reducing memory usage. It is typically used for arrays of characters or small data types.

 

(b)

(i)Outline three factors considered when selecting an appropriate programming language.

 

1. Project requirements: The language should support the features needed for the project.

2. Performance: The language should be efficient for the task at hand.

3.Developer expertise: The language should be familiar to the development team.

(ii)Explain each of the following approaches to programming:**

(I)Monolithic

A monolithic approach involves writing the entire program as a single, large block of code. It is simple but difficult to maintain and debug.

(II)Visual

Visual programming involves using graphical elements to create programs. It is often used in environments like Visual Basic or Scratch.

 

(c)Differentiate between bubble and selection sort techniques.

Bubble Sort: Repeatedly swaps adjacent elements if they are in the wrong order. It is simple but inefficient for large datasets.

Selection Sort: Selects the smallest element from the unsorted portion and swaps it with the first unsorted element. It is more efficient than bubble sort but still not optimal for large datasets.

 

(d)Write a segment code in C programming language that deletes an element from a queue data structure.

“`c

int deleteElement(int queue[], int *front, int *rear) {

if (*front == -1) {

printf(“Queue is empty.”);

return -1;

}

int item = queue[*front];

if (*front == *rear) {

*front = *rear = -1;

} else {

(*front)++;

}

return item;

}

“`

 

Question 7

 

(a)Explain two benefits of a compiler in programming.

1. Optimization: Compilers optimize code for better performance and efficiency.

2. Error Detection: Compilers detect syntax and semantic errors before execution.

 

(b)Outline four factors to consider when naming constant identifiers.

1. Descriptiveness: The name should describe the purpose of the constant.

2. Readability: The name should be easy to read and understand.

3. Consistency: Follow a consistent naming convention.

4. Avoid reserved words: Do not use keywords or reserved words as identifiers.

 

(c)Write a program in Pascal language that would prompt a user to enter two numbers. The program then computes the sum of the two numbers using a function and displays the results.**

“`pascal

program SumCalculator;

var

a, b: integer;

 

function Add(x, y: integer): integer;

begin

Add := x + y;

end;

 

begin

write(‘Enter first number: ‘);

readln(a);

write(‘Enter second number: ‘);

readln(b);

writeln(‘Sum: ‘, Add(a, b));

end.

“`

 

(d)The following elements are stored in an array: 45, 34, 65, 30, 25, and 56. Write a program in C language that would search for the element 30 and display an appropriate message. Use linear search technique.

#include <stdio.h>

int main() {

int arr[] = {45, 34, 65, 30, 25, 56};

int n = sizeof(arr) / sizeof(arr[0]);

int i, found = 0;

for (i = 0; i < n; i++) {

if (arr[i] == 30) {

found = 1;

break;

}

}

if (found) {

printf(“Element 30 found at index %d.”, i);

} else {

printf(“Element 30 not found.”);

}

return 0;

}

Question 8

 

(a)Outline six conversion specifiers used in C programming language.**

1. `%d` – Integer

2. `%f` – Float

3. `%c` – Character

4. `%s` – String

5. `%lf` – Double

6. `%x` – Hexadecimal

 

(b)

(i)Outline two importance of creating subprograms when programming.**

1. Modularity: Subprograms break down complex tasks into smaller, manageable parts.

2. Reusability: Subprograms can be reused in different parts of the program or in other programs.

 

(ii)Susan created a documentation for a program. Outline four elements that she could have included to it for easy referencing.**

1. Program Description: A brief overview of the program’s purpose.

2. Function List: A list of all functions and their purposes.

3. Input/Output Details: Description of the program’s inputs and outputs.

4. Code Comments: Inline comments explaining the code logic.

 

(c)Draw a program flowchart that would declare two sides of a rectangle as constant with values 70 and 130 respectively. The program then calculates and outputs the area of the rectangle.**

“`

Start

|

v

Declare constants: side1 = 70, side2 = 130

|

v

Calculate area = side1 * side2

|

v

Output area

|

v

End

“`

(d)Write a program in C language that prompts a user to enter three different numbers. The program then determi

nes and displays the largest among the numbers.

 

#include <stdio.h>

int main() {

int a, b, c;

printf(“Enter three different numbers: “);

scanf(“%d %d %d”, &a, &b, &c);

if (a > b && a > c) {

printf(“%d is the largest.”, a);

} else if (b > a && b > c) {

printf(“%d is the largest.”, b);

} else {

printf(“%d is the largest.”, c);

}

return 0;

}

 

THIS IS THE LAST PRINTED PAGE.

 

2920/103

July 2021