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

Program

The document contains a series of programming tasks and their corresponding solutions, covering various topics such as string manipulation, sorting algorithms, searching algorithms, data structures, file handling, and SQL queries. Each task is presented with a brief description, followed by the implementation in Python or SQL. Additionally, there are acknowledgments for support received during the project.

Uploaded by

mohdhaani9517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Program

The document contains a series of programming tasks and their corresponding solutions, covering various topics such as string manipulation, sorting algorithms, searching algorithms, data structures, file handling, and SQL queries. Each task is presented with a brief description, followed by the implementation in Python or SQL. Additionally, there are acknowledgments for support received during the project.

Uploaded by

mohdhaani9517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Q1 Program that reads a line and prinesie

Number of uppercase letters


Number of lowercase letters
Number of alphabets
Number of digits

Ans1:-
line= Input("Enter a Line:")
lowercount =uppercount =0
digitcount = alphacount=0
for a in line:
if a.islower():
lowercount+= 1
elif a.isupper():
uppercount+=1
elif a.isdigit():
digitcount+=1
elif a.isalpha():
alphacount +=1
print("Number of uppercase letters:", uppercount)
print ("Number of lowercase letters:", lowercount)
print("Number of alphabets:", alphacount)
print("Number of digits:", digitcount)

OUTPUT:-
Q2 write a program to arrange data using bubble short
Ans2:-
def bubble_sort(arr):
for n in range(len(arr) - 1, 0, -1):
for i in range(n):
if arr[i] > arr[i + 1]:
swapped = True
arr[i], arr[i + 1] = arr[i + 1], arr[i]
arr = [39, 12, 18, 85, 72, 10, 2, 18]
print("Unsorted list is:")
print(arr)
bubble_sort(arr)
print("Sorted list is:")
print(arr)

OUTPUT:-
Q3 write a program to search element using linear
search
A3
def linear_search(arr, target):
for index in range(len(arr)):
if arr[index] == target:
return index
return -1

# Example usage:
arr = [10, 23, 45, 70, 11, 15]
target =int (input("enter number to search in list:-"))

# Function call
result = linear_search(arr, target)

if result != -1:
print(f"Element found at index: {result}")
else:
print("Element not found in the array")

OUTPUT:-
Q4 write a program to input a number and check it is a
palindrome number or not
A4
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

OUTPUT:-
Q5 write the program to print Fibonacci series
A5

nterms = int(input("How many terms? "))


n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
OUTPUT:-
ACKNOWLEDGEMENT

I would like to express my special thanks of gratitude to


my computer teacher (Mrs Aarti ) as well as our principal
(Mrs. Aadesh Sisodiya) who gave me the golden
opportunity to do this wonderful project on the topic(java
programming), which also helped me in doing a lot of
Research and I came to know about so many new things I
am really thankful to them.Secondly, I would also like to
thank my parents and friends who helped me a lot in
finalizing this project within the limited time frame.
Q6 write a program to implement a stack for these
book detail(bookno, book name). That is, now each
item node of the stack contain two types of
information- a book and its name. just implement
push and display operations

Ans8

Stack: implemented as a list

top: integer having position of topmost element in Stack

def cls():
print("\n" * 100)

def isEmpty(stk):
if stk == []:
return True
else:
return False

def Push(stk, item):


stk.append(item)

def Display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top = len(stk) - 1
print(stk[top], "<- top")
for a in range(top - 1, -1, -1):
print(stk[a])

Stack = []
while True:
cls()
print("STACK OPERATIONS")
print("1. Push")
print("2. Display stack")
print("3. Exit")
ch = int(input("Enter your choice (1-3): "))

if ch == 1:
bno = int(input("Enter Book no. to be inserted: "))
bname = input("Enter Book name to be inserted: ")
item = [bno, bname]
Push(Stack, item)
input()
elif ch == 2:
Display(Stack)
input()
elif ch == 3:
break
else:
print("Invalid choice!")
input() # Wait for user input before continuing
Output:-
Q7 Each node of a STACK contains the following
information: (i) Pin code of a city, (ii) Name of city
Write a program to implement following operations in
above stack
(a) PUSH() To push a node in to the stack.
(b) POP() To remove a node from the stack.

Ans7
class CityNode:
def __init__(self, pin_code, city_name):
self.pin_code = pin_code
self.city_name = city_name
self.next = None

class CityStack:
def __init__(self):
self.top = None

def PUSH(self, pin_code, city_name):


new_node = CityNode(pin_code, city_name)
new_node.next = self.top
self.top = new_node
print(f"City {city_name} with Pin Code {pin_code}
pushed to stack.")
def POP(self):
if self.top is None:
print("Stack is empty! Nothing to pop.")
return
popped_node = self.top
self.top = self.top.next # Move top to the next node
print(f"Popped city {popped_node.city_name} with
Pin Code {popped_node.pin_code}.")
del popped_node # Delete the popped node to free
memory

# Display all elements in the stack


def display(self):
if self.top is None:
print("Stack is empty!")
return
current_node = self.top
print("Current Stack contents:")
while current_node is not None:
print(f"City: {current_node.city_name}, Pin Code:
{current_node.pin_code}")
current_node = current_node.next
stack = CityStack()
stack.PUSH(110001, "Delhi")
stack.PUSH(500001, "Hyderabad")
stack.PUSH(400001, "Mumbai")
stack.display()
stack.POP()
stack.display()
Output:-
Q8 Write a program to get student data (roll no, name
and marks) from user and write onto a binary file The
program should be able to get data from the user and
write onto the file as long as the user want

Ans8
import pickle

stufile = open('Stu.dat', 'wb')

ans = 'y'
while ans == 'y':
stu = {}
ro = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))

stu['Rollno'] = ro
stu['Name'] = name
stu['Marks'] = marks

Output :-
Q 9 write a program to increase the salary by rupees
2000 of the employee having epno as 1251 in file
empl.dat.

Ans
import pickle

class Employee:
def __init__(self, empno, name, salary):
self.empno = empno
self.name = name
self.salary = salary

def __repr__(self):
return f"Employee(empno={self.empno},
name='{self.name}', salary={self.salary})"

def load_employees(filename):
try:
with open(filename, 'rb') as file:
employees = pickle.load(file)
return employees
except FileNotFoundError:
print("File not found!")
return []
except EOFError:
return []

def save_employees(filename, employees):


with open(filename, 'wb') as file:
pickle.dump(employees, file)

def increase_salary(filename, empno, increase_amount):


employees = load_employees(filename)
for emp in employees:
if emp.empno == empno:
emp.salary += increase_amount
print(f"Salary of {emp.name} (empno:
{emp.empno}) increased by {increase_amount}. New
salary: {emp.salary}")
break
else:
print(f"Employee with empno {empno} not found.")
save_employees(filename, employees)

if __name__ == "__main__":
filename = 'empl.dat'
increase_salary(filename, 1251, 2000)
Q10 write a program to read following details of sport
performance sport, competition prize bond of your
school and stored into csv file determine with tab
character

Ans
import csv
fh = open("Sport.csv", "w")
swriter = csv.writer(fh, delimiter='\t')
swriter.writerow(['Sport', 'Competitions', 'Prizes won'])
ans = 'y'
i=1
while ans == 'y':
sport= input("Sport name:")
print("Record", i)
comp = int(input("No. of competitions participated:"))
prizes = int(input("Prizes won:"))
srec = [ sport, comp, prizes]
i = 1+1
swriter.writerow(srec)
ans = input("Want to enter more records? (y/n)..")
fh.close()
Output:-
Q11 write a program to create table in my sql

Ans 1
mysql> CREATE TABLE pet (name VARCHAR(20),
owner VARCHAR(20),
species VARCHAR(20), sex CHAR(1),
Output
Q12 given the following students relation

Write SQL commands for (a) to (f) and write output for (g).
(a) To show all information about the students of History
department
(b) To list the names of female students who are in Hindi
department
(c) To list names of all students with their date of
admission in ascending order.
(d) To display student's Name, Fee, Age for male Students
only.
(e) To count the number of student with Age <23.
(f) To inset a new row in the STUDENT table with the
following data:
9, "Zaheer", 36, "Computer", {12/03/97), 230, "M"
(g) Give the output of following SQL statements :
(i) Select COUNT (distinct department) from STUDENT ;
ii) Select MAX (Age) from STUDENT where Sex = "F";
(iii) Select AVG (Fee) from STUDENT where Dateofadm <
(01/01/98};
(iv) Select SUM (Fee) from STUDENT where Dateofadm <
(01/01/98};

Solution

A:-SELECT* FROM Student WHERE Department =


"History";
B:-SELECT Name FROM Student WHERE sex = "F" and
Department = "Hindi";
C:-SELECT name FROM Student ORDER BY Dateofadm;
D:-SELECT Name, Fee, Age FROM Student WHERE sex
= "M";
E:-SELECT COUNT(*) FROM Student WHERE Age < 23;
F:- INSERT INTO Student

VALUES (9, "Zaheer", "Computer", "12/03/97", 230, "M");


G:- (i) 3 (ii) 25
(iii) 216
(iv) 1080

Q14. With reference to following relations PERSONAL


and JOB answer the questions that follow:

Create following tables such that Empno and Sno are


not null and unique, date of birth is after
'12-Jan-1960', name is never blank, Area and Native
place is valid, hobby, dept is not empty, salary is
between 4000 and 10000.
TABLE :- PERSONAL

TABLE :- JOB
(a) Show empno, name and salary of those who have
Sports as hobby.
(b) Show name of the eldest employee.
(c) Show number of employee area wise.
(d) Show youngest employees from each Native place.
(e) Show Sno, Name, Hobby and Salary in descending
order of Salary.
Show the hobbies of those whose name pronounces
as 'Abhay'.
(g) Show the appointment date and native place of
those whose name starts with 'A' or ends in 'd'.
(h) Show the salary expense with suitable column
heading of those who shall retire after 20-jan-2006.
(i) Show additional burden on the company in case
salary of employees having hobby as sports, is
increased by 10%.
() Show the hobby of which there are 2 or more
employees.
(k) Show how many employee shall retire today if
maximum length of service is 20 years.
(1) Show those employee name and date of birth who
have served more than 17 years as on date.
(m) Show names of those who earn more than all of
the employees of Sales dept.
(n) Increase salary of the employees by 5% of their
present salary with hobby as Music or they have
completed atleast 3 years of service.
(0) Write the output of:
(i) Select distinct hobby from personal;
(ii) Select avg(salary) from personal, job where
Personal. Empno
('Agra','Delhi');
(iii) Select count(distinct Native_place) from personal.
Job.Sno and Area in
(iv) Select name, max(salary) from Personal, Job
where Personal.Empno - Job.Sno;
(p) Add a new tuple in the table Personal essentially
with hobby as Music.
(q) Insert a new column email in Job table
(r) Create a table with values of columns empno,
name, and hobby.
(s) Create a view of Personal and Job details of those
who have served less than 15 years.
(f) Erase the records of employee from Job table
whose hobby is not Sports.
(u) Remove the table Personal.

A:-SELECT P.EMPNO, P.NAME, J.Salary


FROM PERSONAL P, JOB J
WHERE P.EMPNO = J.Sno AND P.Hobby = 'Sports';

Output
B:-SELECT name
FROM personal
WHERE dobirth = (
SELECT MIN(dobirth)
FROM personal
);

Output
+------+
| name |
+------+
| Amit |
+------+

C:-SELECT Area, COUNT(Sno) AS Employee_Count


FROM Job
GROUP BY Area;
Output

D:-
SELECT Name, `Native-place`, dobirth
FROM personal
WHERE dobirth = (SELECT MAX(dobirth)
FROM personal p2
WHERE personal.`Native-place` = p2.`

E:-
SELECT SNO, NAME, HOBBY, SALARY
FROM PERSONAL, JOB
WHERE PERSONAL.EMPNO = JOB.SNO
ORDER BY SALARY DESC;

Output:-

F:-
SELECT HOBBY
FROM PERSONAL
WHERE Name = 'abhay' or Name = '
Output
G:-
SELECT App_date, nativeplace
FROM personal, job
WHERE personal.empno = job.sno
AND (Name LIKE 'A%' OR Name LIKE '%d') ;

Output

H:-
SELECT Salary AS "Salary Expense"
FROM Job
WHERE `Retd_date` > '2006-01-20';
Output
I:-
SELECT SUM(Salary * 0.1) AS "Additional Burden"
FROM PERSONAL, JOB
WHERE PERSONAL.EMPNO = JOB.SNO AND HOBBY = 'SPORTS' ;

Output

J:-
SELECT Hobby
FROM PERSONAL
GROUP BY Hobby
HAVING COUNT(*) >= 2;

Output
K:-
SELECT COUNT(*)
FROM Job
WHERE DATEDIFF(CURDATE(), App_date) >= 20 * 365;

Output

L:-
SELECT P.Name, P.Dobirth
FROM Personal P, Job J
WHERE P.Empno = J.Sno AND J.Retd_date > CURDATE() AND DATEDIFF(CURDATE(),
J.App_date) >17*365

Output
M:-
SELECT Name
FROM Personal, job
where personal.Empno = job.Sno
and job.Salary > ( select max(salary)
from job
where dept = 'sales');
Output:-
No output because no employee who salary is greater
than the highest salary in sales department

N:-
UPDATE Job J, Personal P
SET J.Salary = (J.Salary * 0.05 ) + J.Salary
WHERE J.Sno = P.Empno
AND (P.Hobby = 'Music'
OR DATEDIFF(CURDATE(), J.App_date) >= 3 * 365);
Output
(o)

1.
Select distinct hobby from personal ;

Output

2.
Select avg(salary) from personal, job where Personal.Empno = Job.Sno and
Area in ('Agra','Delhi') ;

Output

3.
Select count(distinct Native_place) from personal;
Output

4.
Select name, max(salary)
from Personal, Job where Personal.Empno = Job.Sno ;

Output
+------+--------------------+
| name | max(salary) |
+------+---------------------+
| Amit | 8500 |
+------+---------------------+
Explanation

The given query retrieves the maximum salary from the 'Job' table and pairs it with the
corresponding employee name from the 'Personal' table based on the matching Empno
and Sno values. However, including a non-group field like 'name' in the select-list
means it will return the value from the first record of the group for the 'name'
field. Therefore, 'Amit' is the first record in the 'Personal' table, the query returns 'Amit'
as the value for the 'name' field.

(p)
INSERT INTO Personal (Empno, Name, Dobirth, `Native-place`, Hobby)
VALUES (130, 'Amruta', '1990-05-15', 'Chennai', 'Music');

Q:-
ALTER TABLE Job
ADD COLUMN Email VARCHAR(55);

R:-
insert into empdetails(empno, name, hobby)
select empno, name, hobby
from personal ;
S)
CREATE VIEW LessThan15YearsView AS
SELECT * FROM Personal p, Job j
WHERE p.Empno = j.Sno AND
DATEDIFF(CURDATE(), J.App_date) < 15 * 365;

T) )
DELETE j
FROM Job j, Personal p
WHERE j.Sno = p.Empno AND p.Hobby <> 'Sports';

U)
DROP TAbLE Personal;
Q 13 ) Write SQL queries for (a) to (f):

(a) To show Book name, Author name and Price of


books of First Publ. publishers,
(b) To list the names from books of Text type.
(c) To display the names and price from books in
ascending order of their price.
(d) To increase the price of all books of EPB
Publishers by 50.
(e) To display the Book_Id, Book_Name and
Quantity_Issued for all books which have been issued
query will require contents from both the tables.)
(f) To insert a new row in the table Issued having the
following data: "F0003", 1
(g) Give the output of the following queries based on
the above tables:
(1) SELECT COUNT(*) FROM Books;
(ii) SELECT MAX(Price) FROM Books WHERE
Quantity>=15;
(iii) SELECT Book_Name, Author_Name FROM Books
WHERE Publishers = "EPB":
(iv) SELECT COUNT (DISTINCT Publishers) FROM
Books WHERE Price >= 400;
Ans
A)SELECT Book Name, Author Name, Price FROM
Books WHERE Publishers = "First Publ.";
B)SELECT Book Name FROM Books WHERE Type
"Text";
C) SELECT Book Name, Price FROM Books ORDER
BY Price;
D) UPDATE Books SET Price Price +50 WHERE
Publishers = "EPB";
E)SELECT Books. Book_Id, Book_Name,
Quantity_Issued FROM Books, Issued WHERE
Books. Book_Id = Issued.Book_Id;
F)INSERT INTO Issued VALUES ("F0003", 1);
G) 1) 5
2) 750
3) Fast cook Lata kapoor
My First C++ Brain & Brooke
4) 1

You might also like