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

CPS LAB MANUAL - 1-1

Uploaded by

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

CPS LAB MANUAL - 1-1

Uploaded by

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

23CSE101

COMPUTATIONAL PROBLEM SOLVING

LAB MANUAL

Department of computer and communication Engineering


Amrita School of Engineering
Amrita Vishwa Vidyapeetham, Amaravati Campus

Name: M. Bindhu Sree


Verified by: Roll no: AV.SC.U4CSE24226

S No Title Date Page No Signature

1
LAB 1 Sequence& flowcharts 24-09-24
Algorithm for adding two numbers 5
A
B Algorithm for swapping of two 6
numbers
C Algorithm for area of rectangle 7

D Algorithm to calculate simple interest 8

E Algorithm to calculate the average of 9


three number
LAB 2 Selection& flowcharts 1-10-24
Algorithm for odd or even checker 10
A
B Algorithm to calculate grade of 11
student
C Algorithm for checking eligibility 12

for vote
D Algorithm to leap year checker 13

E Algorithm to performing mathematical 14


operations
LAB 3 Looping& flowcharts 08-10-24
Algorithm for print values to and from 15
A
B Algorithm to print the multiplication 16
table for given number
C Algorithm for Fibonacci sequence 17

generator
D Algorithm for factorial calculator 18

E Algorithm for sum of digits of the given 19


number
LAB 4 Simple python programs 15-10-24
Area of rectangle 20
A
B Simple interest 21

C Compound interest 22

D Adding of two numbers 23

E Swapping of two numbers 23

2
S No Title Date Page No Signature
LAB 5 Programs on operators 22-10-24
Arithmetic operator 24
A
B Assignment operator 25

C Logical operator 26

D Bitwise operator 27

E Special operator 28

F Comparison operator 29

LAB 6 Programs on selections 22-10-24


Driving Eligibility of a person 30
A

B increasing triangle pattern 31

C decreasing triangle pattern 32

D pyramid pattern 33

E numbers in an increasing triangle 34

pattern
F Largest of three numbers
G Electricity bill calculator
H Bus fare calculation
I Hospital bill calculation
J Cinema tickets pricing
K Largest among three number
L Season based on month
M Largest among 4 numbers
LAB 7 Looping python programs
A Biggest among 4 numbers
B Sum of digits of a number
C Fibonacci sequence
D Factorial of a number
E Number is prime
F Largest in a list
G Sum of even number in range
H Multiplication table

I Print letter ‘PYTHON’


3
J Types fruits
K Range of number (1,5)
LAB 8 Patterns programs
A Square pattern
B Increasing triangle
C Decreasing triangle
D Pyramid pattern
E Number in increasing triangle
LAB 9 Data types
A Numeric data type
B Boolean data type
C Python sets
D Dictionary data types
E Sequence data types
LAB 10 Array program
A Create an array
B Accessing an array element
C Slicing an array
D Modify an array element
E Add elements to an array
LAB 11 Function programs
A Defining a function
B Calling a function
C Parameters and arguments a
function
D Returning a function
E Default argument on a
function
LAB 12 Recursion programs
A Factorial calculation using
recursion
B Fibonacci using recursion
C Check if the number is even or
odd
4
D Check if the string is
palindrome or not
E Find the greatest common
divisor of two numbers

LAB-1
a) Write an algorithm for adding of two numbers
Flowchart:

5
Input:

Output:

b) Write an algorithm on swapping of two numbers.


Flowchart:
Input:

6
Output:

7
c) Write an algorithm on area of rectangle
Flowchart:
Input:

Output:

8
d) Write an algorithm for calculation of simple interest
Flowchart:
Input:

Output:

9
e) Write an algorithm for average of two numbers
Flowchart:
Input:

Output:

10
LAB-2
a) Write an algorithm on odd or even checker
Flowchart:
Input:

Output:

11
b) Write an algorithm to calculate the grade of the student.
Flowchart:
Input:

Output:

12
c) Write an algorithm on eligibility of voting
Flowchart:
Input:

Output:

13
d) Write an algorithm on leap year checker.
Flowchart:
Input:

Output:

14
e) Write an algorithm on performing mathematical operations
Flowchart:
Input:

Output:

15
LAB-3
a) Write an algorithm for print to and from values.
Flowchart:
Input:

Output:

16
b) Write an algorithm to print a multiplication of table
Flowchart:
Input:

Output:

c) Write an algorithm for Fibonacci sequence generator


17
Flowchart:
Input:

Output:

d) Write an algorithm of factorial calculator

18
Flowchart:
Input:

Output:

19
e) Write an algorithm for reverse of numbers
Flowchart:
Input:

Output:

20
LAB-4
a) Write a program on area of rectangle
Syntax:
length = float (input ("Enter the length of the rectangle: "))
width = float (input ("Enter the width of the rectangle: "))
area = length * width
print (f"The area of the rectangle is: {area}")
Input:

Output:

21
b) Write a program on simple interest
Syntax:
P = float (input ("Enter the principal amount: "))
R = float (input ("Enter the rate of interest: "))
T = float (input ("Enter the time (in years): "))
SI = (P * R * T) / 100
Print (f"The simple interest is: {SI}")

Input:

Output:

22
c) Write a program on compound interest
Syntax:
P = float (input ("Enter the principal amount: "))
R = float (input ("Enter the rate of interest: "))
T = float (input ("Enter the time (in years): "))
CI = P * (1 + R / 100) ** T - P
Print (f"The compound interest is: {CI}")

Input:

Output:

23
d) Write a program on adding of two numbers
Syntax:
num1 = float (input ("Enter the first number: "))
num2 = float (input ("Enter the second number: "))
sum = num1 + num2
print (f"The sum of {num1} and {num2} is: {sum}")

Input:

Output:

24
LAB-5
a) Write a program on arithmetic operators
Syntax:
a=7
b=2
print ('Sum: ', a + b)
print ('Subtraction: ', a - b)
Print ('Multiplication: ', a * b)
print ('Division: ', a / b)
print ('Floor Division: ', a // b
print ('Modulo: ', a % b)
print ('Power: ', a ** b)
Input:

Output:

25
b) Write a program on assignment operator
Syntax:
a = 40
b=8
print ('a=b:', a==b)
print ('a+=b:', a + b)
print ('a-=b:', a-b)
print ('a*=b:', a*b)
print ('a%=b:', a % b)
print ('a**=b:', a**b)
print ('a//=b:', a//b)

Input:

Output:

26
c) Write a program on logical operator
Syntax:
a = True
b = False
print (a and b)
print (a or b)
print (not a)
Input:

Output:

27
d)Write a program on bitwise operator
Syntax:
X=8
Y=2
print (X&Y)
print(X|Y)
print (X^Y)
print (X >> 2)
print (X << 1)
Input:

Output:

28
e)Write a program on special operator
Syntax:
a = [1, 2, 3]
b=a
c = [1, 2, 3]
print (a is b)
print (a is c)
Input:

Output:

29
f) Write a program on comparison operator
Syntax:
a=5
b=2
print ('a == b =', a == b)
print ('a! = b =', a! = b)
print ('a > b =', a > b)
print ('a < b =', a < b)
print ('a >= b =', a >= b)
print ('a <= b =', a <= b)
Input:

Output:

30
LAB-6
a) Write a program on eligibility of driving of a person
Syntax:
age = int (input ("Enter your age: "))
if age >= 18:
print ("You are eligible to drive.")
else:
print ("You are not eligible to drive.")
Input:

Output:

31
b)Write a program on ATM withdrawal
Syntax:
balance = float (input ("Enter your balance: "))
withdraw_amount = float (input ("Enter amount to withdraw: "))
if balance >= withdraw amount:
print ("Withdrawal allowed.")
else:
print ("Insufficient balance.")
Input:

Output:

32
c) Write a program on grading system
Syntax:
score = int (input ("Enter your score: "))
if score >= 90:
grade = 'A'
Elif score >= 80:
grade = 'B'
else:
grade = 'C'
print (f"Your grade is {grade}.")

Input:

Output:

33
d)Write a program on even and odd checker
Syntax:
number = int (input ("Enter a number: "))
if number % 2 == 0:
print ("The number is even.")
else:
print ("The number is odd.")

Input:

Output:

34
e)Write a program on leap year checker
Syntax:
year = int (input ("Enter a year: "))
if (year % 4 == 0 and year % 100! = 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

Input:

Output:

35
f) Write a program on finding the largest of three
numbers
Syntax:
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))
largest = max(a, b, c)
print(f"The largest number is {largest}.")
Input:

Output:

36
g) Write a program on calculating electricity bill
Syntax:
units = int (input ("Enter units consumed: "))
if units <= 100:
bill = units * 3
elif units <= 300:
bill = 100 * 3 + (units - 100) * 5
else:
bill = 100 * 3 + 200 * 5 + (units - 300) * 8
print (f"Total bill: ₹{bill}")
Input:

Output:

37
h) Write a program on calculating bus fare
Syntax:
distance = int(input("Enter distance in kilometers: "))
if distance <= 5:
fare = 10
else:
fare = 10 + (distance - 5) * 2
print(f"Total bus fare: ₹{fare}")
Input:

Output:

38
i) Write a program on calculating of hospital bill
Syntax:
days = int(input("Enter days stayed: "))
late_night = int(input("Late-night treatment? (1 for yes, 0 for no): "))
insurance = int(input("Insurance coverage? (1 for yes, 0 for no): "))

if days <= 5:
bill = days * 2000
elif days <= 10:
bill = 5 * 2000 + (days - 5) * 1500
else:
bill = 5 * 2000 + 5 * 1500 + (days - 10) * 1000

if late_night == 1:
bill *= 1.2
if insurance == 1:
bill *= 0.85

print(f"Total hospital bill: ₹{bill}")


Input:

Output:

39
j) Write a program on calculating cinema ticket pricing
Syntax:
tickets = int(input("Enter number of tickets: "))
if tickets <= 50:
total_cost = tickets * 250
elif tickets <= 150:
total_cost = 50 * 250 + (tickets - 50) * 400
else:
total_cost = 50 * 250 + 100 * 400 + (tickets - 150) * 600
total_cost -= 1000 # Discount for purchasing more than
150 tickets
print(f"Total cost: ₹{total_cost}")

Input:

Output:

40
k) Write a program on calculating largest among 3 numbers
(nest)
Syntax:
a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

c = int(input("Enter third number: "))

if a>=b:

if a>=c:

largest =a

else:

largest =c

else:

if b>=c:

largest =b

else:

largest=c

print(f"the largest number is{largest:}.")

Input:

Output:

41
i) Write a program on finding seasons based on months
Syntax:
month = int (input ("Enter month number (1-12): "))

if month in [12, 1, 2]:


season = "Winter"
elif month in [3, 4, 5]:
season = "Spring"
elif month in [6, 7, 8]:
season = "Summer"
elif month in [9, 10, 11]:
season = "Fall"
else:
season = "Invalid month number."

Print (f"The season is {season}.")


Input:

Output:

42
m) Write a program on calculating biggest among
four numbers
Syntax:
a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))
c = int (input ("Enter the third number: "))
d = int (input ("Enter the fourth number: "))

if a >= b:
if a >= c:
if a >= d:
largest = a
else:
largest = d
if c >= d:
largest = c
else:
largest = d
else:
if b >= c:
if b >= d:
largest = b
else:
largest = d
else:
if c >= d:
largest = c
else:
largest = d
print (f"The largest number is {largest}.")

Input:

Output:

43
LAB-7
a) Write a program on biggest number among 4 numbers
Syntax:
numbers = []
count = 0 # Initialize counter

# Get 4 numbers from the user using a while loop


while count < 4:
num = int(input(f"Enter number {count + 1}: "))
numbers.append(num)
count += 1 # Increment counter

largest = numbers[0] # Assume the first number is the largest

index = 1 # Initialize index to start from the second element


while index < len(numbers):
if numbers[index] > largest:
largest = numbers[index]
index += 1 # Move to the next number
print(f"The largest number is {largest}.")

Input:

Output:

44
b) Write a program on calculating sum of digits of a numbers
Syntax:
number = int (input ("Enter a number: "))

sum_of_digits = 0
# Use a while loop to extract each digit and add to the sum
while number > 0:
digit = number % 10 # Get the last digit
sum_of_digits += digit # Add the digit to the sum
number //= 10 # Remove the last digit from the number
print (f"The sum of the digits is {sum_of_digits}.")

Input:

Output:

45
c)Write program on Fibonacci sequence
Syntax:
n = int(input("Enter the number of terms in the Fibonacci sequence: "))
a, b = 0, 1
count = 0 # Initialize the counter
print("Fibonacci sequence:")
while count < n:
print(a, end=" ") # Print the current term
a, b = b, a + b # Update 'a' and 'b' to the next terms
count += 1 # Increment the counter

Input:

Output:

46
d)Write program on factorial of number
Syntax:
number = int(input("Enter a number: "))
factorial = 1
i = 1 # Initialize counter
# Use a while loop to calculate factorial
while i <= number:
factorial *= i # Multiply factorial by the current number
i += 1 # Increment counter
print(f"The factorial of {number} is {factorial}.")

Input:

Output:

47
e)Write a program to check if a number is prime
Syntax:
number = int(input("Enter a number: "))

is_prime = True

i = 2 # Start checking from 2

# Use a while loop to check divisibility up to the square root of the number

while i <= int(number ** 0.5):

if number % i == 0:

is_prime = False

break # Exit loop if a divisor is found

i += 1 # Increment i to check the next number

if is_prime and number > 1:

print(f"{number} is a prime number.")

else:

print(f"{number} is not a prime number.")

Input:

Output:

48
f) Write a program on largest number in a list
Syntax:
numbers = []

count = int(input("How many numbers will you enter? "))

i = 0 # Initialize counter

# Get 'count' numbers from the user using a while loop

while i < count:

num = int(input(f"Enter number {i + 1}: "))

numbers.append(num)

i += 1 # Increment counter

largest = numbers[0] # Assume the first number is the largest

j = 1 # Start from the second element in the list

while j < len(numbers):

if numbers[j] > largest:

largest = numbers[j]

j += 1 # Move to the next number

print(f"The largest number is {largest}.")

Input:

Output:

49
g) Write a program sum of even numbers in a range
Syntax:
def sum_even_numbers(start, end):

return sum(i for i in range(start, end+1) if i % 2 == 0)

start_range = int(input("Enter the start of the range: "))

end_range = int(input("Enter the end of the range: "))

result = sum_even_numbers(start_range, end_range)

print("The sum of even numbers in the range is:", result)

Input:

Output:

50
h)Write a program on multiplication table generator
Syntax:
number = int(input("Enter a number: "))

i = 1 # Start from 1

# Use a while loop to print the multiplication table

while i <= 10:

print(f"{number} x {i} = {number * i}")

i += 1 # Move to the next multiplier

Input:

Output:

51
i)Write a program on printing letter ‘PYTHON’
Syntax:
import time
word = "PYTHON"
for letter in word:
print(letter)
time.sleep(1)

Input:

Output:

52
j) Write a program on types of fruits
Syntax:
fruit = ['apple', 'orange', 'mango']
for f in fruit:
print ("The current fruit is:", f)
print ("End of for")

Input:

Output:

53
K)Write a program on range of numbers (1,5)
Syntax:
numbers = [1, 2, 3, 4, 5]
for Num in numbers:
print (Num)
else:
print ("All numbers have been printed.")

Input:

Output:

54
LAB-8
a)Write a program to print a square pattern of 5 row and 5
columns
Syntax:
for i in range(5):
# Inner loop for columns
for j in range(5):
print("*", end=" ")
print()

Input:

Output:

55
b)Write a program to print an increasing triangle pattern
Syntax:
n=5

for i in range(n): # Loop from 1 to 5 (for 5 rows)

# Inner loop for columns

for j in range(i+1): # Loop from 0 to i-1

print("*", end=" ") # Print a star and stay on the same line

print() #

Input:

Output:

56
c)Write a program to print an decreasing triangle pattern
Syntax:
n=5

for i in range(n): # Loop from 1 to 5 (for 5 rows)

# Inner loop for columns

for j in range(i,n): # Loop from 0 to i-1

print("*", end=" ") # Print a star and stay on the same line

print() #

Input:

Output:

57
d)Write a program to print a pyramid pattern
Syntax:

n = int(input("Enter the number of rows: "))

for i in range(n): # Outer loop for rows

for j in range(n - i - 1): # Loop for spaces

print(" ", end="") # Print spaces to align the pyramid

for j in range(i + 1): # Loop for stars

print("*", end=" ") # Print stars with a space for pyramid shape

print() # Move to the next line after each row

Input:

Output:

58
e)Write a program to print numbers in an increasing triangle
pattern
Syntax:
# Get the number of rows from the user

n = int(input("Enter the number of rows needed: "))

# Outer loop for rows

for i in range(n): # Loop through rows

# Inner loop for numbers in each row

for j in range(i + 1): # Loop from 0 to i

print(j + 1, end=" ") # Print numbers starting from 1

print() # Move to the next line after each row

Input:

Output:

59
LAB-9
a)Write a program on numeric data types
Syntax:
a = 42

print(type(a))

b = 3.14159

print(type(b))

c = 1 + 2j

print(type(c))

# Type Conversion

x = float(a)

y = int(b)

z = complex(a, b)

print(x, y, z)

Input:

Output:

60
b)Write a program on Boolean data type
Syntax:
def boolean_data_type():

# Boolean Literals

true_literal = True

false_literal = False

print(f"Boolean Literals: {true_literal} (Type: {type(true_literal)})")

print(f"Boolean Literals: {false_literal} (Type: {type(false_literal)})")

#convert of data type to Boolean

print("\nconvert of data type to Boolean :")

print(bool(0))

print(bool(1))

print(bool(""))

print(bool("Hello"))

#Comparison operation

print("\nComparison operation :")

a=5

b = 10

print(a == b)

print(a != b)

print(a > b)

# Boolean Operations

print("\nBoolean Operations:")

print("True and True:", True and True)

print(f"True and False:", True and False)

print(f"False and True:", False and True)

print(f"False and False:", False and False)

print(f"True or True:", True or True)

print(f"True or False:", True or False)

print(f"False or True:", False or True)

print(f"False or False:", False or False)

print(f"Not True:", not True)

print(f"Not False:", not False)

Input:

61
Output:

62
c)Write a program on set program
Syntax:
my_set = {1, 2, 3, 4, 5}

another_set = set([1, 2, 3, 4, 5])

print("my set=", my_set)

print("another set=", another_set)

# Adding elements

my_set.add(6)

print("add set=", my_set)

# Removing elements

my_set.remove(3)

print("remove set=", my_set)

# Discard method (won't raise an error if the element is not found)

my_set.discard(10)

print("discart set=", my_set)

set1 = {1, 2, 3}

set2 = {3, 4, 5}

union_set = set1.union(set2)

print("union set=", union_set)

intersection_set = set1.intersection(set2)

print("intersection set=", intersection_set)

difference_set = set1.difference(set2)

print("difference set=", difference_set)

symmetric_difference_set = set1.symmetric_difference(set2)

print("symmetric_difference_set=", symmetric_difference_set)

my_set.clear()

print("my set=", my_set)

Input:

63
Output:

64
d)Write a program on dictionary operation
Syntax:
# Creating a dictionary of student grades

grades = {"Alice": 85, "Bob": 92, "Charlie": 88}

# Accessing a value

print(grades["Alice"])

print(grades["Charlie"])

print(grades["Bob"])# Output: 85

# Adding a new key-value pair

grades["David"] = 90

# Updating an existing value

grades["Alice"] = 95

# Removing a key-value pair

del grades["Bob"]

# Iterating through the dictionary

for student, grade in grades.items():

print(f"{student}: {grade}")

Input:

Output:

65
e)Write a program on sequence datatype
Syntax:
my_list = [1, 2, 3, 4, 5]

print(my_list)

# Modifying a list

my_list[0] = 10

print(my_list)

my_tuple = (1, 2, 3, 4, 5)

print(my_tuple)

my_string = "Hello, world!"

print(my_string)

first_element = my_list[0]

print(first_element)

sub_list = my_list[1:4]

print(sub_list)

combined_list = my_list + [6, 7, 8]

print(combined_list)

repeated_list = my_list * 2

print(repeated_list)

is_in_list = 3 in my_list

print(is_in_list)

for item in my_list:

print(item)

Input:

66
Output:

67
LAB-10
a)Write a program to create an array
Syntax:
import array as arr
# 'i' stands for integer type
numbers = arr.array('i', [1, 2, 3, 4])
print(numbers)
Input:

Output:

68
b)Write a program to accessing an array element
Syntax:
numbers = [1, 2, 3, 4, 5]
print(numbers[0])
print(numbers[2])
Input:

Output:

69
c)Write a program to slicing an array
Syntax:
numbers = [1, 2, 3, 4, 5]
print(numbers[1:3])
Input:

Output:

70
d)Write a program to modify an array element
Syntax:
import array as arr
numbers = arr.array('i', [1, 2, 3, 4, 5])
numbers[1] = 10
print(numbers)
numbers[1:3] = arr.array('i', [20, 30])
print(numbers)
Input:

Output:

71
e)Write a program to add elements to an array
Syntax:
numbers = []
numbers.append(5)
print("Added 5 to the list:", numbers)
numbers.extend([6, 7])
print("Extended the list with 6 and 7:", numbers)
Input:

Output:

72
LAB-11
a)Write a program on defining a function
Syntax:
def greet():
print('Hello World!')
Input:

Output:

73
b)Write a program on calling a function
Syntax:
def greet():
print('Hello World!')
Input:

Output:

74
c)Write a program on parameters and arguments of a function
Syntax:
def greet_user(name): # 'name' is a parameter
print(f"Hello, {name}!")
greet_user("Alice") # Output: Hello, Alice!
Input:

Output:

75
d)Write a program on returning values of a function
Syntax:
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
Input:

Output:

76
e)Write a program on default parameters of a functions
Syntax:
def greet_user(name="Guest"):
print(f"Hello, {name}!")
greet_user() # Output: Hello, Guest!
greet_user("Bob") # Output: Hello, Bob!
Input:

Output:

77
LAB-12
a) Write a program on factorial calculation using recursion
Syntax:
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x - 1)
num = 5
print(f"The factorial of {num} is {factorial(num)}")
Input:

Output:

78
b) Write a program on Fibonacci using recursion
Syntax:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n_terms = 10
if n_terms <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci sequence:")
for i in range(n_terms):
print(fibonacci(i))

Input:

Output:

79
c)Write a program to check if the number is even or odd
Syntax:
def is_even(n):

if n == 0:

return True

elif n == 1:

return False

else:

return is_even(n - 2)

def is_odd(n):

return not is_even(n)

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

if is_even(number):

print(f"{number} is even.")

else:

print(f"{number} is odd.")

Input:

Output:

80
d)Write a program to check if the string is palindrome
Syntax:
def is_palindrome(s):

if len(s)<1:

return True

else:

if s[0]==s[-1]:

return is_palindrome(s[1:-1])

else:

return False

a=str(input("enter a string"))

if (is_palindrome(a)== True):

print("the number is palindrome")

else:

print("the number is not palindrome")

Input:

Output:

81
f) Write a program to find the greatest common divisor of two
number
Syntax:
def gcd(a, b):

if b == 0:

return a

else:

return gcd(b, a % b)

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

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

Input:

Output:

82

You might also like