$A&P
$A&P
DATE:13/01/2024
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 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:
Mathematical set
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.
a) Debugging
b) Program linking
✅ 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"
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
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.
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"
Case-Sensitivity in Programming:
✅ Valid: count
❌ Invalid: class, def
✅ Good: total_sales
❌ Poor: ts, x
04. Define framework in python and give two (2) examples. (4marks)
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.
Flask
Summary:
05. List all steps followed to push and pop in stack. (5marks)
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:
class Stack:
def __init__(self):
self.stack = []
def pop(self):
else:
# Usage
s = Stack()
s.push(20)
s.pop()
Key Notes:
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)
Assumed Operation:
Output:
a = 20
b=3
sum = a + b
07. Explain IDE in python and give two (2) examples. (3marks)
IDE in Python
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:
Key Features:
Summary:
08. Explain four (4) rules for switch statement in C language. (4marks)
Example:
int x = 3;
switch(x) { // Valid
Invalid Example:
int x = 5;
switch(x) {
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 3: printf("Three");
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) {
Summary of Rules:
09. Describe any two (2) main types of errors available in a programming
language. (2marks)
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):
number = 5
A Key Differences:
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
INPUT arr[i]
END FOR
PRINT arr[i]
END FOR
STOP
Python Implementation
arr = []
for i in range(n):
arr.append(value)
# Step 4: Display the array in reverse order
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:
50
40
30
20
10
11. Write a C program that will display odd numbers from 50 to 10.
(5marks)
C Program
#include <stdio.h>
int main() {
if (i % 2 != 0) {
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
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
scanf("%d", &day);
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:
return 0;
Explanation:
Output Examples:
Example 1:
Enter a number (1-7) to display the corresponding day of the week: 3
Wednesday
Example 2:
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>
return a + b;
int main() {
scanf("%d", &num1);
scanf("%d", &num2);
return 0;
}
Explanation:
Sample Output:
Example 1:
Enter the first number: 10
Example 2:
14. Consider the following code snippet. Int i = 10; int n = i++%5; (5marks)
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;
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))?
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:
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:
For Loop:
o Iterates over a sequence (like a list, tuple, or range) or an
iterable object.
o Syntax:
# Code block
While Loop:
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:
count = 0
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.
For Loop:
o More readable and concise when working with sequences or
iterables.
o Example:
For Loop:
o More readable and concise when working with sequences or
iterables.
o Example:
While Loop:
o Less concise, but more flexible for dynamic conditions.
7. Performance
Marks Grades
Above 75 O
60-75 A
50-60 B
40-50 C
Less than 40 D
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:
Pseudo code
START
Input marks
If marks > 75
grade ← "O"
grade ← "A"
Else if marks >= 50 AND marks < 60
grade ← "B"
grade ← "C"
Else
grade ← "D"
End If
Print grade
END
Python Implementation
# Determine grade
grade = "O"
grade = "A"
grade = "B"
grade = "C"
else:
grade = "D"
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)
(a! = 7)
((c>=15) ||(d>a))
((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
Final Table
18. A) analyze the following program and provide its output. (5marks)
#include<stdio.h>
Int main ()
Int 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).
#include<stdio.h>
int main() {
int 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) Realloc function in C:
Syntax:
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:
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++
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.
#include<iostream>
return a + b;
return a + b;
return a + b + c;
int main() {
cout << "Addition of two integers: " << intResult << endl;
cout << "Addition of two floats: " << floatResult << endl;
cout << "Addition of three integers: " << intTripleResult << endl;
return 0;
Output:
Explanation:
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.
Pseudo Code:
BinarySearch(arr, target):
low ← mid + 1 // Ignore the left half (move the low pointer)
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.
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:
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:
Here is a JavaScript object that stores the product name and its price, then
outputs the details:
let product = {
displayProductDetails: function() {
};
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