Programming Questions With Answers
Programming Questions With Answers
Question 1
Write a program to find the factorial of a number using recursion in Python.
Answer
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
# Example usage
print(factorial(5)) # Output: 120
Question 2
How do you reverse a string in Python? Write a function to demonstrate.
Answer
def reverse_string(s):
return s[::-1]
# Example usage
print(reverse_string('hello')) # Output: 'olleh'
Question 3
Write a program to check if a number is prime in Java.
Answer
public class PrimeCheck {
public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
x = [1, 2, 3]
y=x
x.append(4)
print(y)
Answer
The output is [1, 2, 3, 4].
Explanation: In Python, lists are mutable and y is a reference to the same list as x.
Question 5
Write a program to find the greatest common divisor (GCD) of two numbers using Euclid's
algorithm in Python.
Answer
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# Example usage
print(gcd(48, 18)) # Output: 6