1.
Write a function named mult() that accepts two floating-point numbers as a
parameters, multiplies these two numbers and display the result
The function mult() can excuite by using Python function as follow
Takes two floating point numbers(x and y) as a parameters
Multiplies them
Display the result using print ().
def mult(x: float, y: float) -> None:
result = x * y
print("The result of mltiplication is:", result)
Example, mult(2.5, 2.0)
The result of mltiplicatiom is : 5.0
2. Write a function that accepts a year as a user input and returns a one if the year
is a leap year or a zero if it is not.
Python function can excuite as follow
The function takes the year as user input
It applies the leap year rule:
Divisible by 4 and not divisible by 100, or divisible by 400.
Returns 1 if true, otherwise 0.
So the function write as
def is_leap_year():
year = int(input("Enter a year: "))
if (year % 4 = = 0 and year % 100 ! = 0) or (year % 400 = = 0):
return 1
else:
return 0
3. Write a program that can be used to play a number guessing game. The player is
first asked for the number of games he wishes to play. Each game gives the player
a maximum of three chances to guess a number chosen randomly. If the player
makes a correct guess, he is given a score depending on the number of guesses he
has made (10, 8, or 5). The final score is given as a percentage with some
complementary remarks.
Frist Let us discribe how it work
Player chooses how many games to play
For each game:
Random number (1–10) is chosen.
Player has 3 attempts.
Score: 10 (first try), 8 (second try), 5 (third try).
After all games, percentage score is calculated.
Final remark is given based on performance.
So the full Python program:
import random
def number_guessing_game():
# Ask player how many games they want to play
total_games = int(input("How many games would you like to play? "))
total_score = 0
max_score = total_games * 10 # Each game has a maximum score of 10
for game in range(1, total_games + 1):
print(f"\n--- Game {game} ---")
secret_number = [Link](1, 10) # Random number between 1 and 10
score = 0
for attempt in range(1, 4): # 3 chances
guess = int(input(f"Attempt {attempt}: Guess the number (1–10): ")
if guess = = secret_number:
if attempt = = 1:
score = 10
elif attempt = = 2:
score = 8
else:
score = 5
print(f"✅ Correct! You scored {score} points.")
break
else:
print("❌ Wrong guess.")
if score = = 0:
print(f"Out of chances! The correct number was {secret_number}.")
total_score + = score
# Calculate final percentage
percentage = (total_score / max_score) * 100
print("\n= = = Final Results = = =")
print(f"Your total score: {total_score}/{max_score} ({percentage:.2f}%)")
# Complementary remarks
if percentage = = 100:
print(" Excellent! Perfect guessing!")
elif percentage > = 70:
print("very good! You did it.")
elif percentage > = 40:
print(" good, keep practicing.")
else:
print(" good luck next time!")
4. Concder the following function
int foo(int x)
static int k = x; // initialized only once
if (x = = 0)
return 0;
if (x < 0)
return k + foo(-x);
else {
int y = foo(x - 1);
return k + y + 1;
What will this program compute?
Step 1: Understand the static int k = x;
static means k is initialized only once, during the first call of foo.
Its value stays constant across all recursive calls.
So the first argument passed to foo() decides k.
Step 2: Behavior for positive x
Let’s try an example:
Call foo(3)
First call: k = 3 (static).
Since x > 0:
y = foo(2)
return 3 + y + 1
Now compute foo(2):
y = foo(1)
return 3 + y + 1
Compute foo(1):
y = foo(0) = 0
return 3 + 0 + 1 = 4
So foo(1) = 4.
Then foo(2) = 3 + 4 + 1 = 8.
Then foo(3) = 3 + 8 + 1 = 12.
So foo(3) = 12.
Step 3: General Pattern for positive n
We can derive:
foo(1) = k + 1
foo(2) = k + (k+1) + 1 = 2k + 2
foo(3) = k + (2k+2) + 1 = 3k + 3
foo(4) = k + (3k+3) + 1 = 4k + 4
Looks like:
foo(n) = n \cdot (k+1)
Since k is the first argument passed, if we called foo(m), then:
foo(m) = m \cdot (m+1)
Step 4: Behavior for negative x
If x < 0:
return k + foo(-x);
So it flips -x positive and adds k.
If the first call is negative, then k itself will be negative, which changes the whole
formula.
Example: foo(-2) (first call) → k = -2.
Since x < 0:
return -2 + foo(2)
Now foo(2) with k=-2:
foo(1) = -2 + foo(0) + 1 = -1
foo(2) = -2 + (-1) + 1 = -2
So final result = -2 + (-2) = -4.
5. Describe the difference between a local auto variable and a local static variable.
Local Auto Variable (default in C/C++)
Declared inside a function (or block).
Storage duration: Created when the function is called, destroyed when the function
ends.
Scope: Visible only inside that function (or block).
Default initialization: Garbage/undefined value (if not explicitly initialized).
Keyword: auto (but in C/C++ it is default, so usually omitted).
Local Static Variable
Declared inside a function, but with static.
Storage duration: Allocated only once, and persists for the entire program run.
Scope: Still local (only accessible inside that function).
Default initialization: Automatically initialized to 0 if not explicitly set.
Feature Local Auto Variable Local Static Variable
Created & destroyed with Created once, persists till program
Lifetime
function ends
Scope Local to function/block Local to function/block
Default value Garbage (uninitialized) 0 (if not explicitly initialized)
Behavior on
Resets each call Remembers value across calls
calls
6. Given the following code:
int sum(int 0)
if(n= =0)
return 0;
else
return(n+sum(n-1));
int sum(int n)
{
a) show the terminating condition
if (n == 0)
return 0;
This stops the recursion.
b) show the recursive part
return n + sum(n - 1);
This reduces the problem size (n decreases each time).
c) hand trace this peace of code for n=4 and find the output.
Let’s expand step by step:
1. sum(4)
→ 4 + sum(3)
2. sum(3)
→ 3 + sum(2)
3. sum(2)
→ 2 + sum(1)
4. sum(1)
→ 1 + sum(0)
5. sum(0)
→ 0 (terminating condition)
Now substitute back:
sum(1) = 1 + 0 = 1
sum(2) = 2 + 1 = 3
sum(3) = 3 + 3 = 6
sum(4) = 4 + 6 = 10
7. Write a recursive program that
a. Checks whether a given word is palindrome. A word is plaindrom if it has same
spelling when we read it from left to right and vice versa (e.g noon)
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// Recursive function to check palindrome
bool isPalindrome(char str[], int start, int end) {
if (start >= end) // Terminating condition
return true;
if (str[start] != str[end]) // Characters mismatch
return false;
return isPalindrome(str, start + 1, end - 1); // Recursive step
int main() {
char word[100];
printf("Enter a word: ");
scanf("%s", word);
if (isPalindrome(word, 0, strlen(word) - 1))
printf("The word '%s' is a palindrome.\n", word);
else
printf("The word '%s' is NOT a palindrome.\n", word);
return 0;
Example:
Input: noon → Output: palindrome
Input: hello → Output: NOT palindrome
b. Checks whether two one dimensional arrays of the same size are identical (have
the same elements)
#include <stdio.h>
#include <stdbool.h>
// Recursive function to check if arrays are identical
bool areIdentical(int arr1[], int arr2[], int size, int index) {
if (index == size) // All elements checked
return true;
if (arr1[index] != arr2[index]) // Mismatch found
return false;
return areIdentical(arr1, arr2, size, index + 1); // Recursive step
int main() {
int n, i;
printf("Enter size of arrays: ");
scanf("%d", &n);
int arr1[n], arr2[n];
printf("Enter elements of first array:\n");
for (i = 0; i < n; i++)
scanf("%d", &arr1[i]);
printf("Enter elements of second array:\n");
for (i = 0; i < n; i++)
scanf("%d", &arr2[i]);
if (areIdentical(arr1, arr2, n, 0))
printf("The arrays are identical.\n");
else
printf("The arrays are NOT identical.\n");
return 0;
Example:
Input: arr1 = {1, 2, 3}, arr2 = {1, 2, 3} → Output: identical
Input: arr1 = {1, 2, 3}, arr2 = {1, 4, 3} → Output: NOT identical
8. Determine the values displayed by each cout statement in the following
program:
#include <iostream.h>
int firstnum=20;
void display(void);
int main()
int firstnum =20;
cout<<”\nthe value of firstnum is<<firstnum<<endl;
display();
return 0;
void display(void)
cout<<”the value of firstnum is now<<endl;
return;
Step for execution:
I. Global variable
II. int firstnum = 20; // Global scope
III. Inside main()
IV. int firstnum = 20; // Local variable (shadows the global one)
V. cout << "\nthe value of firstnum is " << firstnum << endl;
This prints the local variable (20).
Output:
VI. the value of firstnum is 20
VII. Inside display()
VIII. cout << "the value of firstnum is now " << firstnum << endl;
No local variable firstnum inside display(), so it refers to the global
firstnum (which is also 20).
Output:
IX. the value of firstnum is now 20
9.
10.