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

Class_12_CS_Programs

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)
8 views

Class_12_CS_Programs

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

Python Programs for Class 12 Computer Science

Question 1:
Write a program in Python to calculate the factorial of a number entered by the user.

Answer:

def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result

num = int(input("Enter a number: "))


print(f"Factorial of {num}: {factorial(num)}")

Question 2:
Write a program in Python to calculate the sum of the first N natural numbers.

Answer:

def sum_of_natural_numbers(n):
return n * (n + 1) // 2

n = int(input("Enter the value of N: "))


print(f"Sum of first {n} natural numbers: {sum_of_natural_numbers(n)}")

Question 3:
Write a Python program to check whether a number is prime or not.

Answer:

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

num = int(input("Enter a number: "))


if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Question 4:
Write a program in Python to reverse a string entered by the user.

Answer:

def reverse_string(s):
return s[::-1]

s = input("Enter a string: ")


print(f"Reversed String: {reverse_string(s)}")

Question 5:
Write a Python program to implement a binary search algorithm on a sorted list.

Answer:

def binary_search(arr, x):


low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1

arr = sorted(list(map(int, input("Enter sorted elements separated by space: ").split())))


x = int(input("Enter the element to search for: "))
result = binary_search(arr, x)
if result != -1:
print(f"Element {x} found at index {result}.")
else:
print(f"Element {x} not found.")

You might also like