0% found this document useful (0 votes)
6 views38 pages

$A&P

The document outlines the structure and instructions for an exam on Algorithm and Programming Fundamentals, scheduled for January 13, 2024. It consists of three sections with a total of 100 marks, covering topics like Python programming, variable naming rules, stack operations, IDEs, and error types in programming. Additionally, it includes specific questions and examples related to Python frameworks, switch statements in C, and common programming errors.

Uploaded by

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

$A&P

The document outlines the structure and instructions for an exam on Algorithm and Programming Fundamentals, scheduled for January 13, 2024. It consists of three sections with a total of 100 marks, covering topics like Python programming, variable naming rules, stack operations, IDEs, and error types in programming. Additionally, it includes specific questions and examples related to Python frameworks, switch statements in C, and common programming errors.

Uploaded by

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

OPTION/TRADE: SOFTWARE DEVELOPMENT

SUBJECT/EXAM: ALGORITHM AND PROGRAMMING FUNDAMENTALS


DURATION: 3 HOURS

DATE:13/01/2024

INSTRUCTIONS TO CANDIDATES (QUESTION PAPER

This Exam paper is composed of Three Sections (A, B, and C). Follow the
instructions given below, and answer the indicated questions for a total of
100 marks

Section A: Fourteen (14) questions, all Compulsory 55 marks

Section B: Among the five (5) questions, attempt any three (3) 30 marks

Section C: Among the two (2) questions, attempt any one (1) 15 marks

Allowed materials:

 Blue or black pen

 Mathematical set

SECTION A: Attempt all questions (55 marks)

01. What is python? (2marks)

Python is a high-level, interpreted, and general-purpose programming


language. It is widely used for various applications due to its simplicity,
readability, and versatility. Python was created by Guido van Rossum and
first released in 1991.

Key Features of Python:

1. Easy to Learn and Use: Python has a clean and simple syntax that
resembles natural language, making it an excellent choice for
beginners.
2. Interpreted: Python code is executed line by line, which helps in quick
debugging and prototyping.
3. Dynamically Typed: Variables in Python do not require explicit
declaration of their type, as the type is determined at runtime.
4. Extensive Standard Library: Python comes with a large standard
library, providing modules and functions for tasks like file I/O, web
development, data analysis, and more.
5. Cross-Platform: Python is platform-independent, meaning you can
run Python programs on different operating systems (Windows,
macOS, Linux) with little or no modification.
6. Supports Multiple Paradigms: Python supports procedural, object-
oriented, and functional programming paradigms.

Common Uses of Python:

1. Web Development: Frameworks like Django and Flask.


2. Data Science and Machine Learning: Libraries like Pandas, NumPy,
and TensorFlow.
3. Automation/Scripting: Writing scripts to automate repetitive tasks.
4. Game Development: Using frameworks like Pygame.
5. Scientific Computing: Libraries such as SciPy and Matplotlib.
6. Artificial Intelligence: Tools like PyTorch and Scikit-learn.
7. Cybersecurity: For tasks like penetration testing and network
analysis.

02. Define the following terms applied in algorithm: (4marks)

a) Debugging

Debugging is the process of identifying, analyzing, and resolving errors or


bugs in a computer program or algorithm. These errors can be syntax
errors, logical errors, or runtime errors that prevent the program from
functioning as intended. Debugging involves tools and techniques such as:

 Using print statements to trace the program flow.


 Employing debuggers to step through code execution.
 Reviewing code to identify logical flaws.

b) Program linking

Program linking refers to the process of combining multiple object files or


code modules into a single executable program. This involves resolving
references between functions, variables, or libraries from different parts of a
program. Linking can be of two types:

1. Static Linking: All required code is combined into a single executable


file at compile time.
2. Dynamic Linking: Some components, such as libraries, are loaded
into memory at runtime rather than being included in the executable.
02. State any five (5) rules of naming a variable (5marks)

 Must Start with a Letter or Underscore (_):


A variable name must begin with a letter (A-Z or a-z) or an underscore (_). It
cannot start with a digit.

 ✅ Valid: name, _temp


 ❌ Invalid: 1name, -var

 No Special Characters Allowed:


Variable names can only include alphanumeric characters (letters and digits)
and underscores (_). They cannot contain spaces or special symbols like @,
$, %, etc.

 ✅ Valid: count_1
 ❌ Invalid: count#1, var@temp

 Case-Sensitive:
Variable names are case-sensitive, meaning myVar and MyVar are treated as
distinct variables.

Here are two examples to demonstrate that variable names are case-sensitive:

Example 1:

name = "Alice"

Name = "Bob"

print(name) # Output: Alice

print(Name) # Output: Bob

 Explanation: name and Name are treated as two different variables


because of the difference in capitalization.

age = 25

AGE = 30

print(age) # Output: 25

print(AGE) # Output: 30
Explanation: age and AGE refer to separate variables due to
the difference in case, even though their names look similar.

value = 100

Value = 200

print(value) # Output: 100

print(Value) # Output: 200

Explanation:

 value and Value are treated as two different variables because of the
difference in capitalization.
 Python (and many programming languages) distinguishes between
uppercase and lowercase letters, making variable names case-
sensitive.

Case-sensitive refers to the distinction made between


uppercase and lowercase letters in a given context. In
programming, a case-sensitive system treats variables,
identifiers, or text as different entities based on whether
letters are capitalized or not.

Examples of Case Sensitivity:

1. Variable Names:

age = 25

Age = 30

AGE = 35

print(age) # Output: 25

print(Age) # Output: 30

print(AGE) # Output: 35

Here, age, Age, and AGE are treated as three distinct variables.
Strings:

"Hello" != "hello"

The string "Hello" is different from "hello" due to the uppercase


"H" in the first string.

Case-Sensitivity in Programming:

 Case-Sensitive Languages: Python, Java, JavaScript, and C++


distinguish between uppercase and lowercase letters.
 Non-Case-Sensitive Languages: SQL and HTML are examples where
case is usually ignored (e.g., SELECT and select are equivalent).

 Cannot Use Reserved Keywords:


A variable name cannot be the same as a reserved keyword or built-in
function of the programming language (e.g., if, for, while, print).

 ✅ Valid: count
 ❌ Invalid: class, def

 Should Be Descriptive and Meaningful (Best Practice):


While not strictly enforced, it is recommended to use meaningful names that
reflect the purpose of the variable to improve code readability.

 ✅ Good: total_sales
 ❌ Poor: ts, x

04. Define framework in python and give two (2) examples. (4marks)

A framework in Python is a pre-built collection of modules, libraries, and tools that


provide a structured foundation for building applications. Frameworks simplify
development by offering reusable components, best practices, and an organized
way to handle common programming tasks, such as routing, database interactions,
and user interface design.

Examples of Frameworks in Python:

1. Django
o A high-level, full-stack web framework for building robust and
scalable web applications.
o It emphasizes the "Don't Repeat Yourself" (DRY) principle
and includes built-in features like ORM (Object-Relational
Mapping), authentication, and a powerful admin interface.

Example Use Case: Building e-commerce websites or content


management systems (CMS).

pip install django

Flask

 A lightweight and minimalist web framework ideal for small to medium-


sized applications.
 It is a micro-framework that allows developers to build web
applications while giving flexibility to choose additional tools and
libraries.

Example Use Case: Creating REST APIs or small web services.

pip install flask

Summary:

Frameworks in Python provide developers with tools and a standardized way


of building applications, making development faster and more efficient.

05. List all steps followed to push and pop in stack. (5marks)

Steps to Push and Pop in a Stack

A stack is a data structure that operates on a Last In, First Out (LIFO)
principle. Below are the steps to perform push (insertion) and pop (deletion)
operations:

1. Steps to Push (Insert an Element into the Stack):

1. Check if the Stack is Full (Overflow Condition):


o If the stack has a maximum capacity and is already full, an
overflow error occurs.
o If not, proceed to the next step.
2. Increase the Top Pointer (Optional):
o If using an array-based implementation, move the pointer/index
(top) to the next empty position.
3. Add the Element to the Stack:
Insert the new element at the position indicated by the top.
o
4. Update the Stack State:
o Ensure the stack reflects the addition of the new element.

2. Steps to Pop (Remove an Element from the Stack):

1. Check if the Stack is Empty (Underflow Condition):


o If the stack is empty, there is no element to remove, and an
underflow error occurs.
o If not, proceed to the next step.
2. Access the Top Element:
o Retrieve the element at the top of the stack for further processing
or display.
3. Remove the Top Element:
o Decrease the top pointer or remove the element at the current
top position.
4. Update the Stack State:
o Ensure the stack reflects the removal of the element.

Example Implementation in Python:

class Stack:

def __init__(self):

self.stack = []

def push(self, element):

self.stack.append(element) # Step: Add element

print(f"Pushed {element} into the stack.")

def pop(self):

if not self.stack: # Step: Check for underflow

print("Stack Underflow: No elements to pop.")

else:

element = self.stack.pop() # Step: Remove top element

print(f"Popped {element} from the stack.")

# Usage
s = Stack()

s.push(10) # Push step

s.push(20)

s.pop() # Pop step

s.pop()

s.pop() # Pop from an empty stack (underflow)

Key Notes:

 Overflow Condition occurs when trying to push onto a full stack.


 Underflow Condition occurs when trying to pop from an empty stack.
 These steps apply to both array-based and linked-list-based stack
implementations.

06. Find the output of the following program: If the value of a=20, b=3, what
will be the value of the sum? (2marks)

To calculate the sum given a = 20 and b = 3, I need the specific formula or


operation used to compute the "sum." If no formula is provided, I'll assume it
is a simple addition operation.

Assumed Operation:

If the operation is sum = a + b, then:

Sum=a+b=20+3=23\text {sum} = a + b = 20 + 3 = 23sum=a+b=20+3=23

Output:

If the program simply prints the sum:

a = 20

b=3

sum = a + b

print("The value of the sum is:", sum)


The output will be:

The value of the sum is: 23

07. Explain IDE in python and give two (2) examples. (3marks)

IDE in Python

An IDE (Integrated Development Environment) is a software application


that provides a comprehensive environment for writing, editing, testing, and
debugging Python programs. It integrates various developer tools into one
platform to make programming more efficient and productive.

Key Features of an IDE:

1. Code Editor: For writing and editing Python code.


2. Debugger: For identifying and fixing errors in the code.
3. Compiler/Interpreter Integration: To execute Python code directly.
4. Syntax Highlighting: To improve code readability.
5. Code Autocompletion: To suggest code while typing, saving time.
6. Project Management: Tools for organizing and managing large
projects.

Examples of Python IDEs:

1. PyCharm
o Developed by JetBrains, PyCharm is a popular IDE for Python
development.
o It supports advanced features like debugging, version control,
code inspection, and intelligent code completion.
o Ideal for both beginners and professionals.

Key Features:

o Supports web frameworks like Django and Flask.


o Built-in tools for testing and database management.

pip install pycharm

Visual Studio Code (VS Code)

 Developed by Microsoft, VS Code is a lightweight yet powerful code


editor that supports Python through extensions.
 It's popular for its flexibility and support for multiple programming
languages.

Key Features:

 IntelliSense (smart autocompletion).


 Integrated terminal and Git support.
 Extensions for linting, debugging, and more.

Summary:

Using an IDE improves productivity by offering tools that streamline the


process of writing and maintaining Python code. Both PyCharm and VS Code
are widely used and well-suited for Python development.

08. Explain four (4) rules for switch statement in C language. (4marks)

The switch statement in C is a control structure used to perform multi-way


branching. It evaluates an expression and executes the corresponding block of code
based on matching cases. Below are four rules that govern the use of a switch
statement in C:

1. Expression in switch Must Evaluate to a Constant or Integer


Type

 The value passed to the switch statement must be an integer or a value


that can be implicitly converted to an integer (e.g., char).
 Floating-point (float, double) and complex data types are not allowed.

Example:

int x = 3;

switch(x) { // Valid

case 1: printf("One"); break;

case 3: printf("Three"); break;

2. Each case Must Have a Constant or Literal Value


 The values in each case must be constants or literals. Variables or
ranges are not allowed directly in case labels.

Invalid Example:

int x = 5;

switch(x) {

case 1: printf("One"); break;

case x: printf("X"); break; // Error: x is a variable

3. break Statement Terminates a Case

 The break statement is used to exit the switch structure. Without break,
execution will continue to subsequent cases (fall-through behavior).

Example:

int x = 2;

switch(x) {

case 1: printf("One");

case 2: printf("Two"); break; // Without break, execution continues to the


next case

case 3: printf("Three");

// Output: "Two" (if break is included), otherwise "TwoThree"

4. default is Optional but Recommended

 The default case executes if none of the case labels match the
expression. It is optional but recommended to handle unexpected or
invalid input.
Example:

int x = 7;

switch(x) {

case 1: printf("One"); break;

case 2: printf("Two"); break;

default: printf("Default case"); // Executed when no cases match

Summary of Rules:

1. The switch expression must evaluate to an integer or constant.


2. Each case must have a constant value, not a variable or range.
3. Use break to prevent fall-through behavior between cases.
4. Include a default case to handle unmatched conditions.

09. Describe any two (2) main types of errors available in a programming
language. (2marks)

Here are two main types of errors commonly encountered in programming


languages:

1. Syntax Errors

 Definition: Syntax errors occur when the code violates the grammar
or rules of the programming language. These errors are detected
during the compilation or interpretation phase, and the program will
not run until they are fixed.
 Common Causes:
o Missing semicolons (;) in C, C++, or Java.
o Improper indentation in Python.
o Mismatched parentheses, brackets, or braces.
o Misspelled keywords or incorrect syntax usage.
 Example (Python):

print("Hello World" # Missing closing parenthesis

Error Message: SyntaxError: unexpected EOF while parsing


2. Logical Errors

 Definition: Logical errors occur when the program runs without


crashing but produces incorrect or unintended results. These errors are
not detected by the compiler or interpreter, as they result from flaws in
the program's logic.
 Common Causes:
o Incorrect implementation of algorithms.
o Wrong formulas or calculations.
o Misplaced or missing conditional statements.
 Example (Python):

# Intent: Calculate the square of a number

number = 5

result = number * 2 # Logical error: Should be number ** 2

print(result) # Output: 10 (Incorrect)

A Key Differences:

Aspect Syntax Logical


Errors Errors
Detection During compilation or Only through
runtime testing/debugging
Effect Program won’t Program executes but
execute gives wrong output
Fixing Correct syntax Correct program logic

10. Write an algorithm to read n number of values in an array and display


them in reverse order. 4marks

Algorithm to Read n Values in an Array and Display Them in


Reverse Order

1. Start
2. Input the value of n (the number of elements in the array).
3. Initialize an array arr of size n.
4. For i from 0 to n-1:
o Input the value of arr[i].
5. Print the message "Array in reverse order:"
6. For i from n-1 to 0:
o Print the value of arr[i].
7. Stop

Pseudocode

START

INPUT n

DECLARE array arr[n]

FOR i FROM 0 TO n-1 DO

INPUT arr[i]

END FOR

PRINT "Array in reverse order:"

FOR i FROM n-1 TO 0 DO

PRINT arr[i]

END FOR

STOP

Python Implementation

Here is how the algorithm can be implemented in Python:

# Step 1: Input the number of elements

n = int(input("Enter the number of elements: "))

# Step 2: Initialize an array

arr = []

# Step 3: Read elements into the array

for i in range(n):

value = int(input(f"Enter element {i+1}: "))

arr.append(value)
# Step 4: Display the array in reverse order

print("Array in reverse order:")

for i in range(n-1, -1, -1):

print(arr[i])

Example Execution:

Input:
Enter the number of elements: 5

Enter element 1: 10

Enter element 2: 20

Enter element 3: 30

Enter element 4: 40

Enter element 5: 50

Output:

Array in reverse order:

50

40

30

20

10

11. Write a C program that will display odd numbers from 50 to 10.
(5marks)

Here’s a C program that displays odd numbers from 50 to 10 in reverse order:

C Program

#include <stdio.h>
int main() {

// Start from 50 and decrement to 10

for (int i = 50; i >= 10; i--) {

// Check if the number is odd

if (i % 2 != 0) {

printf("%d\n", i); // Print the odd number

return 0;

Explanation:

1. Loop Initialization: The for loop starts with i = 50 and decrements until i >=
10.
2. Odd Number Check: Inside the loop, the condition i % 2 != 0 is used to
determine if i is odd.
3. Printing Odd Numbers: If the condition is true, the value of i is printed.

Output

When the program is executed, it will display:

49

47

45

43

41

39
37

35

33

31

29

27

25

23

21

19

17

15

13

11

This outputs all the odd numbers between 50 and 10 in reverse order.

12. Develop a C program to display the days of the week by using switch
case statement. (5marks)

Here’s a C program that uses a switch statement to display the day of the week
based on user input:

C Program

#include <stdio.h>

int main() {

int day;
// Prompt the user to enter a number

printf("Enter a number (1-7) to display the corresponding day of the week:


");

scanf("%d", &day);

// Use a switch case to display the day of the week

switch (day) {

case 1:

printf("Monday\n");

break;

case 2:

printf("Tuesday\n");

break;

case 3:

printf("Wednesday\n");

break;

case 4:

printf("Thursday\n");

break;

case 5:

printf("Friday\n");

break;

case 6:

printf("Saturday\n");
break;

case 7:

printf("Sunday\n");

break;

default:

printf("Invalid input! Please enter a number between 1 and 7.\n");

return 0;

Explanation:

1. Input: The user enters a number between 1 and 7.


2. Switch Case:
o Each case corresponds to a day of the week (e.g., 1 for Monday, 2 for
Tuesday, etc.).
o The break statement ensures no fall-through between cases.
3. Default Case: If the user enters a number outside the range 1–7, an error
message is displayed.

Output Examples:

Example 1:
Enter a number (1-7) to display the corresponding day of the week: 3

Wednesday

Example 2:

Enter a number (1-7) to display the corresponding day of the week: 8

Invalid input! Please enter a number between 1 and 7.

This program handles user input gracefully and displays the correct day or an error
message for invalid input.
13. Use sum () function to develop a simple C program that will add two
numbers. (5marks)

In C, the sum() function is not a built-in function, so you need to define it yourself.
Here's a simple C program that defines a sum() function to add two numbers:

C Program

#include <stdio.h>

// Function to calculate the sum of two numbers

int sum(int a, int b) {

return a + b;

int main() {

int num1, num2, result;

// Input two numbers

printf("Enter the first number: ");

scanf("%d", &num1);

printf("Enter the second number: ");

scanf("%d", &num2);

// Call the sum() function

result = sum(num1, num2);

// Display the result

printf("The sum of %d and %d is: %d\n", num1, num2, result);

return 0;
}

Explanation:

1. Defining the sum() Function:


o The function sum() takes two integer parameters, a and b, and returns
their sum.
o Syntax: int sum(int a, int b)

2. Input and Output:


o The program prompts the user to enter two numbers.
o It calls the sum() function with the input values and stores the result in
the result variable.
o Finally, it prints the result.

Sample Output:

Example 1:
Enter the first number: 10

Enter the second number: 20

The sum of 10 and 20 is: 30

Example 2:

Enter the first number: -5

Enter the second number: 15

The sum of -5 and 15 is: 10

This program demonstrates a simple use of a user-defined function ( sum()) to add


two numbers in C.

14. Consider the following code snippet. Int i = 10; int n = i++%5; (5marks)

a) What are the values of i and n after the code is executed?

Let’s analyze the given code snippet and determine the values of i and n for both
cases (postfix i++ and prefix ++i):

Code Snippet:
int i = 10;

int n = i++ % 5;

a) Using Postfix Increment (i++)

 Postfix Increment means the value of i is used before it is incremented.

Execution Steps:

1. i = 10 (initial value).
2. n = i % 5:
o The value of i (which is 10) is used in the modulus operation.
o 10 % 5 = 0 (remainder of 10 divided by 5 is 0).
o So, n = 0.
3. After the modulus operation, the postfix increment ( i++) is applied:
o i is incremented by 1.
o i = 11.

Final Values:

 i = 11
 n=0

b) what are the final values of i and n if instead of using the postfix
increment operator (i++), you use the prefix version (++i))?

b) Using Prefix Increment (++i)

 Prefix Increment means the value of i is incremented before it is used.

Execution Steps:

1. i = 10 (initial value).
2. ++i is applied first:
o i is incremented by 1.
o i = 11.
3. n = i % 5:
o The updated value of i (which is now 11) is used in the modulus
operation.
o 11 % 5 = 1 (remainder of 11 divided by 5 is 1).
o So, n = 1.

Final Values:

 i = 11
 n=1

Summary of Results:

Operator Final Value of Final Value of


i n
Postfix (i+ 11 0
+)
Prefix (+ 11 1
+i)

Section B: Attempt any three (3) questions (30 marks)


_____________________________________________________________________________

15. Compare for loop with while loop. (10marks)

Both for loops and while loops are used for iteration, but they differ in their
usage, syntax, and typical use cases. Here's a detailed comparison:

1. Syntax and Structure

 For Loop:
o Iterates over a sequence (like a list, tuple, or range) or an
iterable object.
o Syntax:

for item in iterable:

# Code block

While Loop:

 Repeats as long as a specified condition is true.


 Syntax:

while condition:

# Code block

2. Use Cases

 For Loop:
o Used when the number of iterations is known or when iterating
over a predefined sequence.
o Example: Iterating over a list of numbers or a range.

for i in range(5):

print(i)

While Loop:

 Used when the number of iterations is not known in advance and


depends on a condition.
 Example: Repeating an action until a condition is met.

count = 0

while count < 5:

print(count)

count += 1

3. Condition Handling

 For Loop:
o The loop automatically stops when the sequence is exhausted.
o Typically no explicit condition is used.
 While Loop:
o Requires an explicitly defined condition. If not carefully written, it
can lead to infinite loops.

4. Infinite Loop

 For Loop:
o Rarely leads to an infinite loop unless used improperly (e.g.,
modifying the iterable inside the loop).
 While Loop:
o Can easily result in an infinite loop if the condition never
becomes false.

while True:
print("This is an infinite loop")

5. Control Flow

 Both support break, continue, and else for controlling loop execution.
o Break: Exits the loop prematurely.
o Continue: Skips the current iteration and moves to the next.
o Else: Executes if the loop completes without a break.

6. Readability and Simplicity

 For Loop:
o More readable and concise when working with sequences or
iterables.
o Example:

6. Readability and Simplicity

 For Loop:
o More readable and concise when working with sequences or
iterables.
o Example:

for char in "Hello":


print(char)

 While Loop:
o Less concise, but more flexible for dynamic conditions.

7. Performance

 Performance differences are negligible in most cases. Choice depends


more on readability and use case.

Summary of Key Differences:


Feature For While
Loop Loop
Condition Iterates over a Based on a condition
sequence
Known Ideal for known Ideal for unknown
Iterations iterations iterations
Risk of Infinite Rare Higher
Loop
Flexibilit Limited to Very flexible
y iterables
16. Refer to table below and write an algorithm to print the grade obtained
by a student. 10marks

Marks Grades

Above 75 O

60-75 A

50-60 B

40-50 C

Less than 40 D

Algorithm to Print Grade Based on Marks

Step 1: Start.
Step 2: Input the student's marks (let's call it marks).
Step 3: Check the value of marks against the grade criteria:

 If marks > 75, assign grade "O".


 Else if 60 ≤ marks ≤ 75, assign grade "A".
 Else if 50 ≤ marks < 60, assign grade "B".
 Else if 40 ≤ marks < 50, assign grade "C".
 Else (if marks < 40), assign grade "D".
Step 4: Output the grade.
Step 5: End.

Pseudo code

START

Input marks

If marks > 75

grade ← "O"

Else if marks >= 60 AND marks <= 75

grade ← "A"
Else if marks >= 50 AND marks < 60

grade ← "B"

Else if marks >= 40 AND marks < 50

grade ← "C"

Else

grade ← "D"

End If

Print grade

END

Python Implementation

# Input: Student's marks

marks = float(input("Enter the student's marks: "))

# Determine grade

if marks > 75:

grade = "O"

elif 60 <= marks <= 75:

grade = "A"

elif 50 <= marks < 60:

grade = "B"

elif 40 <= marks < 50:

grade = "C"

else:

grade = "D"

# Output the grade


print(f"The grade obtained by the student is: {grade}")

This algorithm ensures the grade is determined accurately based on the given
criteria.

17. Analyze the expression provided in the first column and complete the
second column of the table below. Assume that a=5, b=10, c=15 and d=0.
(10marks)

EXPRESSION TRUE OR FALSE

(a! = 7)

((c>=15) ||(d>a))

((d/c < (a*b))

(! ((a+d) >= (c-b+1) ))

((c>b)&& (b<a))

Here is the analysis and evaluation of each expression based on the given
values:

Assumptions:

 a = 5, b = 10, c = 15, d = 0
 Logical operators:
o != means "not equal to."
o || means "logical OR."
o && means "logical AND."
o ! means "logical NOT."

Expression Analysis

Expression Evaluation TRUE OR FALSE


(a != 5 != 7 → TRUE TRUE
7)
**((c >= (d >
15)
a))**
(d / c < (a * (0 / 15 < (5 * 10)) → 0 < 50 TRUE
b))
→ TRUE
(!( (a + d) >= (c - b + !( (5 + 0) >= (15 - 10 + 1) ) TRUE
1) )) → !(5 >= 6) → !(FALSE) →
TRUE
((c > b) && (b < (15 > 10) → TRUE AND FALSE
a))
(10 < 5) → FALSE →
FALSE

Final Table

Expression TRUE OR FALSE


(a != TRUE
7)
**((c >=
15)
(d / c < (a * TRUE
b))
(!( (a + d) >= (c - b + TRUE
1) ))
((c > b) && (b < FALSE
a))

18. A) analyze the following program and provide its output. (5marks)

#include<stdio.h>

Int main ()

Int i;

Int arr [5] = {1, 5, 9};

For (i = 0; i < 5; i++) {

Printf ("%d ", arr[i]);

Return 0;

}
a) Program analysis:

The given C program has several issues related to syntax and declaration:

1. Data type declaration (Int): In C, the correct data type should be int
(lowercase).
2. For loop syntax: The keyword For should be lowercase: for.
3. Array initialization: The array arr[5] is initialized with only 3 values
({1, 5, 9}). The remaining elements will be initialized to 0 (the default
value for uninitialized elements in an integer array).

Here’s the corrected version of the program:

#include<stdio.h>

int main() {

int i;

int arr[5] = {1, 5, 9};

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

printf("%d ", arr[i]);

return 0;

Output:

The program will print the values in the array arr[5], which contains the
values {1, 5, 9, 0, 0}. So, the output will be:

15900

Explanation:
 The array arr[5] is initialized with {1, 5, 9}, and the remaining elements
(arr[3] and arr[4]) will default to 0 because no values were assigned to
them.
 The for loop iterates over all 5 elements of the array and prints each
element in sequence.

b) Explain reallot and give its syntax. (5marks)

b) Realloc function in C:

The realloc function in C is used to resize a previously allocated memory


block. It can either shrink or expand the memory block based on the new
size provided.

Syntax:

void* realloc(void* ptr, size_t new_size);

void* realloc(void* ptr, size_t new_size);

 ptr:A pointer to a previously allocated memory block (e.g., allocated


using malloc or calloc).
 new_size: The new size, in bytes, to which the memory block should be
resized.

Key Points:

 If the new size is larger, realloc may allocate a new block of memory,
copy the data from the old block to the new block, and free the old
block.
 If the new size is smaller, the block will be truncated.
 If realloc fails to allocate memory, it returns NULL, and the original block
remains valid.

Example:

int* ptr = (int*)malloc(5 * sizeof(int)); // Allocate memory for 5 integers

// Resize the memory block to hold 10 integers

ptr = (int*)realloc(ptr, 10 * sizeof(int));

In this example, the memory block initially allocated for 5 integers is resized to hold
10 integers.
19. With the help of examples, explain function overloading in C++

Function Overloading in C++

Function overloading is a feature in C++ that allows defining multiple


functions with the same name but different parameters. The functions must
differ in the number or type of their parameters (or both). The compiler uses
the function signature (the number and type of parameters) to differentiate
between overloaded functions.

Key points:

1. Same function name: All overloaded functions have the same name.
2. Different parameters: The functions must differ in the number or
types of parameters (or both).
3. Return type does not count: The return type of the functions
doesn't play a role in distinguishing overloaded functions.
4. Resolved at compile time: The correct version of the function is
called based on the arguments passed during the function call.

Example of Function Overloading:

#include<iostream>

using namespace std;

// Function to add two integers

int add(int a, int b) {

return a + b;

// Function to add two floating point numbers

float add(float a, float b) {

return a + b;

// Function to add three integers


int add(int a, int b, int c) {

return a + b + c;

int main() {

int intResult = add(10, 20); // Calls add(int, int)

float floatResult = add(10.5f, 20.3f); // Calls add(float, float)

int intTripleResult = add(5, 10, 15); // Calls add(int, int, int)

cout << "Addition of two integers: " << intResult << endl;

cout << "Addition of two floats: " << floatResult << endl;

cout << "Addition of three integers: " << intTripleResult << endl;

return 0;

Output:

Addition of two integers: 30

Addition of two floats: 30.8

Addition of three integers: 30

Explanation:

 The function add is overloaded in three ways:


o Two integers: add(int a, int b) adds two integers.
o Two floating-point numbers: add(float a, float b) adds two
floating-point numbers.
o Three integers: add(int a, int b, int c) adds three integers.
 The compiler automatically selects the appropriate function based on
the arguments passed during the function call.
Notes:

 Parameter type and number must differ. Changing the return type
alone won’t allow function overloading.
 Overloaded functions can exist within the same class or scope, as long
as they have different signatures.

Section C: Attempt only one (1) question (15 marks)

20. Write a Pseudo code program of binary search algorithms. (15marks)

Pseudo Code for Binary Search Algorithm

Binary Search is an efficient algorithm for finding an element in a sorted


array or list. It works by repeatedly dividing the search interval in half. If the
value of the target is less than the value in the middle of the interval, the
search continues in the lower half, or if the target is greater, it continues in
the upper half.

Here’s the pseudo code for the Binary Search algorithm:

Pseudo Code:

BinarySearch(arr, target):

low ← 0 // Initial lower bound of the array

high ← length(arr) - 1 // Initial upper bound of the array

while low ≤ high:

mid ← (low + high) / 2 // Find the middle index

if arr[mid] = target: // If the target is found at mid

return mid // Return the index of the target

else if arr[mid] < target: // If target is greater than mid element

low ← mid + 1 // Ignore the left half (move the low pointer)

else: // If target is smaller than mid element


high ← mid - 1 // Ignore the right half (move the high
pointer)

return -1 // If the target is not found, return -1

Explanation:

1. Initialization:
o Set the initial lower bound (low) to 0 (the start of the array).
o Set the upper bound (high) to length(arr) - 1 (the last index of the
array).
2. Loop:
o While low is less than or equal to high, calculate the middle index
(mid).
o Check if the element at the middle index ( arr[mid]) is equal to the
target:
 If yes, return the index mid.
o If arr[mid] is smaller than the target, it means the target must be
in the right half of the array, so we move the low pointer to mid +
1.
o If arr[mid] is larger than the target, it means the target must be in
the left half of the array, so we move the high pointer to mid - 1.
3. Return:
o If the target is not found during the process, return -1 to indicate
that the target is not in the array.

Example:

Suppose we have an array arr = [1, 3, 5, 7, 9, 11], and we want to find the target
9.

 Initially, low = 0, high = 5, and target = 9.


 mid = (0 + 5) / 2 = 2. arr[2] = 5, which is less than 9, so we update low = 3.
 Now, low = 3, high = 5, and mid = (3 + 5) / 2 = 4. arr[4] = 9, which matches
the target, so we return index 4.

Thus, the result will be 4, which is the index of 9 in the array.

This is an O(log n) algorithm, where n is the number of elements in the array.

21. A) Develop a JavaScript program that will calculate volume of (10marks)


A box of length = 30, width = 50 and height=5

(Hint: volume = length * width * height)

A) JavaScript Program to Calculate the Volume of a Box

Here’s a JavaScript program that calculates the volume of a box given the
length, width, and height. The formula to calculate the volume is:

volume=length×width×height\text{volume} = \text{length} \times \text{width} \


times \text{height}volume=length×width×height

// JavaScript program to calculate the volume of a box

// Define the dimensions of the box

let length = 30; // in units (e.g., cm, meters)

let width = 50; // in units

let height = 5; // in units

// Calculate the volume

let volume = length * width * height;

// Output the result

console.log("The volume of the box is: " + volume + " cubic units.");

Explanation:

 We define the length, width, and height of the box with the given values
(30, 50, and 5, respectively).
 The formula volume = length * width * height is used to compute the
volume.
 The result is printed using console.log().

Output:

The volume of the box is: 7500 cubic units.

b) Create a JavaScript object that will store and output (5marks)


Product and price of a commodity.

B) JavaScript Object to Store Product and Price

Here is a JavaScript object that stores the product name and its price, then
outputs the details:

// JavaScript object to store product details

let product = {

name: "Laptop", // Product name

price: 800, // Product price in USD

// Method to display the product and price

displayProductDetails: function() {

console.log("Product: " + this.name);

console.log("Price: $" + this.price);

};

// Output product details

product.displayProductDetails();

Explanation:

 We define a product object with two properties: name (the name of the
product) and price (the price of the product).
 We also add a method displayProductDetails() inside the object to print the
product name and price.
 The this keyword refers to the current object, so this.name and this.price
access the object's properties.

Output:

Product: Laptop
Price: $800

This program allows you to store product details in an object and then display them
using a method within the same object.

END OF ASSESSMENT

You might also like