0% found this document useful (0 votes)
12 views

Programming Questions With Answers

Uploaded by

nsb55920
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)
12 views

Programming Questions With Answers

Uploaded by

nsb55920
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/ 2

Programming Logical 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;
}

public static void main(String[] args) {


System.out.println(isPrime(17)); // Output: true
}
}
Question 4
What is the output of the following Python code?

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

You might also like