1
1. Write a program that prints “Hello World” to the screen.
#R
print("Hello World")
cat("Hello World")
#C
# include <stdio.h>
int main() {
printf("Hello World");
return 0;
}
# Python
print("Hello World")
2. Write a program that asks the user for a number n and prints the sum of the numbers 1
to n.
# Ask the user to enter a number
n <- [Link](readline(prompt = "Enter a number: "))
# Calculate the sum from 1 to n
sum_result <- sum(1:n)
# Print the result
cat("The sum of numbers from 1 to", n, "is", sum_result)
How it works:
1. readline() → Takes input from the user.
2. [Link]() → Converts input to an integer.
3. sum(1:n) → Adds numbers from 1 to n.
4. cat() → Prints the result in a readable format.
Example:
If the user enters:
Enter a number: 5
Output will be:
The sum of numbers from 1 to 5 is 15
3. Write a program that prints a multiplication table for numbers up to 12.
2
# Loop through numbers 1 to 12
for (i in 1:12) {
cat("\nMultiplication Table of", i, "\n")
for (j in 1:12) {
cat(i, "x", j, "=", i * j, "\n")
}
}
How it works:
Outer loop (i) → Selects the number (1 to 12).
Inner loop (j) → Multiplies that number by 1 to 12.
cat() → Prints the formatted output.
📝 Sample Output (First Table Only)
Multiplication Table of 1
1x1=1
1x2=2
...
1 x 12 = 12
It will continue printing tables up to 12 × 12.
4. Write a function that returns the largest element in a list.
# Function to find the largest element in a list
find_largest <- function(lst) {
# Convert list to numeric vector (if needed)
values <- unlist(lst)
# Return the maximum value
return(max(values))
}
# Example usage
my_list <- list(10, 25, 7, 40, 15)
result <- find_largest(my_list)
cat("The largest element is:", result)
How it works:
1. unlist(lst) → Converts the list into a vector.
3
2. max(values) → Finds the largest number.
3. return() → Returns the result.
📝 Output:
The largest element is: 40
Alternative (Without Using max() – Using Loop)
find_largest <- function(lst) {
values <- unlist(lst)
largest <- values[1]
for (i in values) {
if (i > largest) {
largest <- i
}
}
return(largest)
}
5. Write a function that computes the running total of a list.
R Function: Running Total (Cumulative Sum) of a List
A running total means each element is the sum of all previous elements including
itself.
🔹 Method 1: Using Built-in Function (cumsum())
# Function to compute running total
running_total <- function(lst) {
values <- unlist(lst) # Convert list to vector
return(cumsum(values)) # Compute cumulative sum
}
# Example
my_list <- list(2, 4, 6, 8)
result <- running_total(my_list)
4
print(result)
Output:
[1] 2 6 12 20
🔹 Method 2: Without Using cumsum() (Using Loop)
running_total <- function(lst) {
values <- unlist(lst)
total <- numeric(length(values))
total[1] <- values[1]
for (i in 2:length(values)) {
total[i] <- total[i - 1] + values[i]
}
return(total)
}
🔎 How It Works:
unlist() → Converts list into numeric vector.
Loop version → Adds current value to previous total.
Returns a vector of running totals.
6. Write a function that tests whether a string is a palindrome.
R Function: Check if a String is a Palindrome
A palindrome is a word that reads the same forward and backward (e.g., madam,
level).
🔹 Method 1: Simple Version
is_palindrome <- function(str) {
# Convert to lowercase (for case-insensitive check)
str <- tolower(str)
# Reverse the string
reversed <- paste(rev(strsplit(str, "")[[1]]), collapse = "")
# Compare original and reversed
return(str == reversed)
}
5
# Example
is_palindrome("madam")
📝 Output:
[1] TRUE
🔹 Method 2: Ignore Spaces and Special Characters
is_palindrome <- function(str) {
# Convert to lowercase
str <- tolower(str)
# Remove non-alphanumeric characters
str <- gsub("[^a-z0-9]", "", str)
# Reverse the cleaned string
reversed <- paste(rev(strsplit(str, "")[[1]]), collapse = "")
return(str == reversed)
}
# Example
is_palindrome("A man, a plan, a canal: Panama")
📝 Output:
[1] TRUE
🔎 How It Works:
tolower() → Makes comparison case-insensitive
gsub() → Removes spaces and punctuation (optional version)
strsplit() + rev() → Reverses the string
Returns TRUE or FALSE
7. Implement linear search.
R Program: Linear Search Implementation
Linear search checks each element one by one until the target value is found.
🔹 Function to Perform Linear Search
linear_search <- function(arr, target) {
for (i in 1:length(arr)) {
if (arr[i] == target) {
return(paste("Element found at position", i))
6
}
}
return("Element not found")
}
# Example
numbers <- c(10, 25, 30, 45, 50)
result <- linear_search(numbers, 30)
print(result)
📝 Output:
[1] "Element found at position 3"
🔎 How It Works:
1. Loop goes through each element of the vector.
2. Compares each element with the target value.
3. If match is found → returns its position.
4. If no match → returns "Element not found".
✅ Alternative (Return Index Only)
linear_search <- function(arr, target) {
for (i in seq_along(arr)) {
if (arr[i] == target) {
return(i)
}
}
return(-1) # If not found
}
8. Implement binary search.
R Program: Binary Search Implementation
⚠️ Note: Binary search works only on a sorted vector.
🔹 Iterative Version
binary_search <- function(arr, target) {
left <- 1
7
right <- length(arr)
while (left <= right) {
mid <- floor((left + right) / 2)
if (arr[mid] == target) {
return(paste("Element found at position", mid))
}
if (arr[mid] < target) {
left <- mid + 1
} else {
right <- mid - 1
}
}
return("Element not found")
}
# Example (Sorted Vector)
numbers <- c(5, 10, 15, 20, 25, 30)
result <- binary_search(numbers, 20)
print(result)
📝 Output:
[1] "Element found at position 4"
🔎 How It Works:
1. Set left and right pointers.
2. Find middle element.
3. Compare with target:
o If equal → return position.
o If target is larger → search right half.
o If smaller → search left half.
4. Repeat until found or range is empty.
✅ Recursive Version (Optional)
binary_search_recursive <- function(arr, target, left = 1, right = length(arr)) {
if (left > right) {
8
return(-1)
}
mid <- floor((left + right) / 2)
if (arr[mid] == target) {
return(mid)
} else if (arr[mid] < target) {
return(binary_search_recursive(arr, target, mid + 1, right))
} else {
return(binary_search_recursive(arr, target, left, mid - 1))
}
}
9. Implement matrices addition, subtraction and Multiplication
R Program: Matrix Addition, Subtraction, and Multiplication
In R, matrices are created using the matrix() function.
🔹 1. Matrix Addition
# Create two matrices
A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(5, 6, 7, 8), nrow = 2)
# Addition
result_add <- A + B
print("Matrix Addition:")
print(result_add)
🔹 2. Matrix Subtraction
# Subtraction
result_sub <- A - B
print("Matrix Subtraction:")
print(result_sub)
🔹 3. Matrix Multiplication
⚠️ Use %*% operator for matrix multiplication (not *).
# Matrix Multiplication
result_mul <- A %*% B
9
print("Matrix Multiplication:")
print(result_mul)
📝 Sample Output
If:
A= B =
13 57
24 68
Addition:
6 10
8 12
Subtraction:
-4 -4
-4 -4
Multiplication:
23 31
34 46
✅ Combined Function Version (Exam-Friendly)
matrix_operations <- function(A, B) {
cat("Addition:\n")
print(A + B)
cat("Subtraction:\n")
print(A - B)
cat("Multiplication:\n")
print(A %*% B)
}
10. Fifteen students were enrolled in a course. There ages were:
11. 20 20 20 20 20 21 21 21 22 22 22 22 23 23 23
i. Find the median age of all students under 22 years
ii. Find the median age of all students
iii. Find the mean age of all students
iv. Find the modal age for all students
v. Two more students enter the class. The age of both students is 23. What is
now mean, mode and median?
R Code
10
# Given ages of 15 students
ages <- c(20,20,20,20,20,
21,21,21,
22,22,22,22,
23,23,23)
# i) Median age of students under 22 years
under_22 <- ages[ages < 22]
median_under_22 <- median(under_22)
# ii) Median age of all students
median_all <- median(ages)
# iii) Mean age of all students
mean_all <- mean(ages)
# iv) Mode of all students
freq <- table(ages)
mode_all <- [Link](names(freq[freq == max(freq)]))
# Display original results
cat("Median (under 22):", median_under_22, "\n")
cat("Median (all students):", median_all, "\n")
cat("Mean (all students):", mean_all, "\n")
cat("Mode (all students):", mode_all, "\n")
# v) After adding two students aged 23
ages_new <- c(ages, 23, 23)
mean_new <- mean(ages_new)
median_new <- median(ages_new)
freq_new <- table(ages_new)
mode_new <- [Link](names(freq_new[freq_new == max(freq_new)]))
cat("\nAfter adding two students (age 23):\n")
cat("New Mean:", mean_new, "\n")
cat("New Median:", median_new, "\n")
cat("New Mode:", mode_new, "\n")
✅ Expected Output
11
Median (under 22): 20
Median (all students): 21
Mean (all students): 21.33333
Mode (all students): 20
After adding two students (age 23):
New Mean: 21.52941
New Median: 22
New Mode: 20 23
✔ Final Answers (Conceptually)
Median (< 22 years) = 20
Median (all students) = 21
Mean (all students) = 21.33
Mode (all students) = 20
After adding two 23-year-olds:
New Mean = 21.53
New Median = 22
New Mode = 20 and 23 (bimodal)