[go: up one dir, main page]

0% found this document useful (0 votes)
12 views15 pages

Computer Science

The document contains a collection of computer science programs and SQL queries written by Moksha Tyagi, a Class 12 A student. It includes various algorithms such as calculating factorials, checking for prime numbers, and performing database operations like creating tables and querying data. Each program is accompanied by its code and example output, demonstrating practical applications of programming concepts.

Uploaded by

mokanika2007
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 views15 pages

Computer Science

The document contains a collection of computer science programs and SQL queries written by Moksha Tyagi, a Class 12 A student. It includes various algorithms such as calculating factorials, checking for prime numbers, and performing database operations like creating tables and querying data. Each program is accompanied by its code and example output, demonstrating practical applications of programming concepts.

Uploaded by

mokanika2007
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/ 15

COMPUTER

SCIENCE

Name : Moksha Tyagi


Class : 12 A
Roll No. :7
Index
S.NO PROGRAM

1 Factorial of a Number
2 Swapping Two Numbers
3 Checking for Prime Number
4 Fibonacci Sequence
5 Sum of Digits of a Number
6 Reversing a Number
7 Checking for Palindrome
8 Finding the Largest Element in a List
9 Counting Occurrences of an Element in a List
10 Simple Interest Calculation
11 Area of a Circle
12 Converting Celsius to Fahrenheit
13 Finding the GCD of Two Numbers
14 Checking for Armstrong Number
15 Generating Multiplication Table
16 Simple Query – Select All Data from a Single Table (SQL)
17 Select Specific Columns (SQL)
18 Join Two Tables – Inner Join (SQL)
19 Aggregate Function – COUNT (SQL)
20 Select with Condition – WHERE Clause (SQL)
21 Connect to MySQL Database and Create a Table
22 Insert Data into a MySQL Table (Python-MySQL)
23 Query Data from a MySQL Table (Python-MySQL)
24 Update Data in a MySQL Table (Python-MySQL)

Code and Output


1. Factorial of a Number
def factorial(n):
"""Calculates the factorial of a non-negative
integer."""
if n == 0:
return 1
else:
fact = 1
for i in range(1, n + 1):
fact *= i
return fact

num = 5
print(f"The factorial of
{num}is{factorial(num)}")

2. Swapping Two Numbers


def swap_numbers(a, b):
"""Swaps the values of two variables."""
a, b = b, a
return a, b

x = 10
y = 20
x, y = swap_numbers(x, y)
print(f"After swapping: x = {x}, y = {y}")
3. Checking for Prime Number
def is_prime(num):
"""Checks if a number is prime."""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

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

4.Fibonacci Sequence
def fibonacci(n):
"""Generates the first n Fibonacci numbers."""
fib_list = []
a, b = 0, 1
for _ in range(n):
fib_list.append(a)
a, b = b, a + b
return fib_list

num_terms = 10
print(f"Fibonacci sequence up to {num_terms}
terms: {fibonacci(num_terms)}")

5. Sum of Digits of a Number


def sum_of_digits(num):
"""Calculates the sum of digits of a number."""
sum_digits = 0
while num > 0:
digit = num % 10
sum_digits += digit
num //= 10
return sum_digits

number = 12345
print(f"The sum of digits of {number} is
{sum_of_digits(number)}")

6. Reversing a Number
def reverse_number(num):
"""Reverses a number."""
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
return reversed_num

number = 1234
print(f"The reverse of {number} is
{reverse_number(number)}")

7. Checking for Palindrome


def is_palindrome(string):
"""Checks if a string is a palindrome."""
string = string.lower() return string ==
string[::-1]

text = "Racecar"
if is_palindrome(text):
print(f"{text} is a palindrome.")
else:
print(f"{text} is not a palindrome.")

8. Finding the Largest Element in a List


def find_largest(lst):
"""Finds the largest element in a list."""
if not lst:
return "List is empty"
largest = lst[0]
for item in lst:
if item > largest:
largest = item

return largest

The largest element is: 20

9. Counting Occurrences of an Element


in a List
def count_occurrences(lst, element):
"""Counts the occurrences of an element in a
list."""
count = 0
for item in lst:
if item == element:
count += 1
return count

my_list = [1, 2, 2, 3, 2, 4, 2]
element_to_count = 2
print(f"The element {element_to_count} occurs
{count_occurrences(my_list, element_to_count)}
times.")

10. Simple Interest Calculation


def simple_interest(principal, rate, time):
"""Calculates simple interest."""
interest = (principal * rate * time) / 100
return interest
p = 1000
r=5
t=2
si = simple_interest(p, r, t)
print(f"The simple interest is: {si}")

11. Area of a Circle


import math

def area_of_circle(radius):
"""Calculates the area of a circle."""
area = math.pi * radius**2
return area

radius = 7
print(f"The area of the circle is:
{area_of_circle(radius)}")

12. Converting Celsius to Fahrenheit


def celsius_to_fahrenheit(celsius):
"""Converts Celsius to Fahrenheit."""
fahrenheit = (celsius * 9/5) + 32
return fahrenheit

celsius_temp = 25
print(f"{celsius_temp} Celsius is equal to
{celsius_to_fahrenheit(celsius_temp)}
Fahrenheit.")

13. Finding the GCD of Two Numbers

def gcd(a, b):


"""Calculates the greatest common divisor
(GCD) using Euclid's algorithm."""
while b:
a, b = b, a % b
return a

num1 = 48
num2 = 18
print(f"The GCD of {num1} and {num2} is
{gcd(num1, num2)}")

14. Checking for Armstrong Number


def is_armstrong(num):
"""Checks if a number is an Armstrong
number."""
num_str = str(num)
num_digits = len(num_str)
sum_of_powers = 0
for digit in num_str:
sum_of_powers += int(digit)**num_digits
return sum_of_powers == num

number = 153
if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong
number.")

15. Generating Multiplication Table


def multiplication_table(num, limit):
"""Generates a multiplication table for a given
number up to a specified limit."""
for i in range(1, limit + 1):
print(f"{num} x {i} = {num * i}")
number = 5
limit = 10
multiplication_table(number, limit)

16. Simple Query – Select All Data from a


Single Table(MYSQL)
cursor.execute('SELECT * FROM Employees')
all_employees = cursor.fetchall()
print("All Employees:", all_employees)

Output Table:
employee_id first_name last_name
department_id salary

1 John Doe 101 55000


2 Jane Smith 102 60000
3 Alice Johnson 101 70000
4 Bob Brown 103 45000

17. Select Specific Columns(MYSQL)


cursor.execute('SELECT first_name, last_name,
salary FROM Employees')
specific_columns = cursor.fetchall()
print("Specific Columns:", specific_columns)

Output Table:

first_name last_name salary

John Doe 55000


Jane Smith 60000
Alice Johnson 70000
Bob Brown 45000

18. Join Two Tables – Inner Join(MYSQL)


cursor.execute('''
SELECT Employees.first_name,
Employees.last_name,
Departments.department_name
FROM Employees
INNER JOIN Departments ON
Employees.department_id =
Departments.department_id
''')
join_result = cursor.fetchall()
print("Join Result:", join_result)

Output Table:
first_name last_name department_name

John Doe IT
Jane Smith HR
Alice Johnson IT
Bob Brown Marketing

19. Aggregate Function –


COUNT(MYSQL)
cursor.execute('''
SELECT department_id, COUNT(*) AS
num_employees
FROM Employees
GROUP BY department_id
''')
count_result = cursor.fetchall()
print("Count Result:", count_result)

Output Table:
department_id num_employees

101 2
102 1
103 1

20. Select with Condition – WHERE


Clause(MYSQL)
cursor.execute('SELECT first_name, last_name, salary
FROM Employees WHERE salary > 50000')

condition_result = cursor.fetchall()
print("Condition Result:", condition_result)

Output Table:
first_name last_name salary

John Doe 55000


Jane Smith 60000
Alice Johnson 70000

Connect to MySQL Database and Create


a Table
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='password', database='test_db'
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Employees (
employee_id INT AUTO_INCREMENT PRIMARY
KEY,
first_name VARCHAR(100),
last_name VARCHAR(100),
department_id INT,
salary FLOAT
);
''')
conn.commit()
cursor.close()
conn.close()
print("Table 'Employees' created successfully.")

Insert Data into a MySQL Table


import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='test_db'
)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO Employees (first_name, last_name,
department_id, salary)
VALUES (%s, %s, %s, %s)
''', ('John', 'Doe', 101, 55000))
cursor.execute('''
INSERT INTO Employees (first_name, last_name,
department_id, salary)
VALUES (%s, %s, %s, %s)
''', ('Jane', 'Smith', 102, 60000))
conn.commit()
cursor.close()
conn.close()
print("Data inserted into 'Employees' table
successfully.")

Query Data from a MySQL Table


import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='test_db'
)
cursor = conn.cursor()
cursor.execute('SELECT * FROM Employees;')
rows = cursor.fetchall()
print(row)
cursor.close()
conn.close()

Update Data in a MySQL Table


import mysql.connector

conn = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='test_db'
)

cursor = conn.cursor()
cursor.execute('''
UPDATE Employees
SET salary = salary + 5000
WHERE department_id = 101;
''')

conn.commit()
cursor.close()
conn.close()
print("Salary updated for employees in
department 101.")
THANK YOU

You might also like