0% found this document useful (0 votes)
7 views65 pages

Basic Algorithms and Programs in Python

It is algorithm

Uploaded by

vidushisinghlko
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views65 pages

Basic Algorithms and Programs in Python

It is algorithm

Uploaded by

vidushisinghlko
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd

COMPUTER ASSIGNMENT

1.

Aim : Algorithm to check if a number is odd or even

Algorithm:
Step 1: Start the process

Step 2: Get the value of 'a' from user

Step 3: Check whether 'a' is divisible by 2 and the remainder is zero then display as 'even number'
otherwise display as 'odd number'

Step 4: End the process.

Program Code:
name=str(“Vidushi Singh 25BCE10314”)

print(name)

a=int(input("enter a number"))

if (a%2==0):

print("even")

else:

print("odd")

print(“Vidushi Singh”)

print(“25BCE10314”)

Output:
2.

Aim : Algorithm to check if a number is positive ,negative or zero

Algorithm:
Step 1: Start the process

Step 2: Get the value of 'a' from user

Step 3: Check whether the number is greater than zero then display 'positive number' or if the number is
less than zero then display 'negative number' otherwise display 'The number is 0'.

Step 4: End the process.

Program Code:
a=int(input("enter a number"))

if (a<0):

print("negative")

elif (a>0):

print("positive")

elif (a==0):

print("zero")

print(“Vidushi Singh”)

print(“25BCE10314”)

Output:
3.

Aim : Algorithm to check area of triangle,circle,rectangle or square

Algorithm:
Step 1: Start the process

Step 2: Get the user to input the choice of the user whether they want to find the
area of square, rectangle, triangle or circle

Step 3:  If the choice is '1' (Circle):

Prompt the user to enter the radius.

Calculate the area using the formula:

Area=π×radius2

Print the calculated area.

 If the choice is '2' (Rectangle):

Prompt the user to enter the length and width.

Calculate the area using the formula:

Area=length×width

Print the calculated area.

 If the choice is '3' (Square):

Prompt the user to enter the side length.

Calculate the area using the formula:

Area=side2

Print the calculated area.

 If the choice is '4' (Triangle):

Prompt the user to enter the base and height.


Calculate the area using the formula:

Area=21×base×height

Print the calculated area.

 If the choice is '5' (Exit):

Print a message thanking the user.

Use a break statement to exit the loop and end the program.

 If the choice is invalid:

Print an error message asking the user to enter a valid choice.

Step 4: End the process

Program Code:

shape=str(input("enter the shape u want to find area of triangle/ square/ circle/ rectangle"))

if (shape=="triangle"):

a=int(input("base: "))

b=int(input("height"))

print(a*b/2)

elif(shape=="square"):

side=int(input("enter side: "))

print(side*side)

elif(shape=="circle"):

rad=int(input("enter the radius of circle: "))

print(3.14*rad) elif(shape=="rectangle"):

len=int(input("enter the length of rectangle: "))

wid=int(input("enter the width of rectangle: "))


print(len*wid)

print(“Vidushi Singh”)

print(“25BCE10314”)

Output:
4.

Aim:Algorithm to do simple calculations

Algorithm:
Step 1: Start the process

Step 2: Get the user to enter the value of two variables named ‘a’ and ‘b’

Step 3 :Get the user to prompt their choices of the operations to be done on the variables

Step 4:

If Choice 1: Add the two numbers

Choice 2:Subtract the numbers

Choice 3:Divide the number

Choice 4:Multiply the numbers

Step 5: Print the final number

Step 6: End the process

Program Code:
type=str(input("choose the operation u want to perform +,-,/,* : "))

a=int(input("enter a num: "))

b=int(input("enter num2: "))

if(type=="+"):

print(a+b)

elif(type=="-"):

print(a-b)

elif(type=="/"):

print(a/b)

elif(type=="*"):

print(a*b)
print(“Vidushi Singh”)

print(“25BCE10314”)

Output:
5.

Aim: Algorithm to convert Celsius to degree F

Algorithm :
Step 1: Start the Program: The application loads and presents the user interface.

Step 2: Get Input: The program prompts the user to enter a numerical value into a text field.

Step 3:Listen for User Action: The program waits for the user to click either the "Celsius to
Fahrenheit" button or the "Fahrenheit to Celsius" button.

Step 4: Validate Input: When a button is clicked, the program checks if the entered value is a
valid number. If it is not, a message is displayed indicating an invalid input.

Step 5:Perform Calculation:

If the "Celsius to Fahrenheit" button is clicked, the program applies the conversion formula: F =
(C * 9/5) + 32.

If the "Fahrenheit to Celsius" button is clicked, the program applies the conversion formula: C =
(F - 32) * 5/9.

Step 6: Display Result: The program takes the calculated result, formats it to two decimal
places, and displays it in the result area of the application.

Step 7: End the Program.

Program :
type=str(input("input 1 if you want to convert from degree celsius to fahrenhite or input 2 if u want to
convert from degree fahrenhite to degree celsius: "))

if(type=="1"):

val=int(input("degree celsius= "))

print("degree fahrenhite: ",(val*1.8)+32)

elif(type=="2"):

num=int(input("degree fahrenhite: "))

print("degree celsius: ",(num-32)*5/9)

print(“Vidushi Singh”)
print(“25BCE10314”)

Output
6.

Aim: To create an application that takes five marks as input, calculates the percentage, and
assigns a corresponding grade.

Algorithm:
Step 1 Start the Program: The application loads and presents the user interface.

Step 2 Get Input: The program prompts the user to enter five separate marks.

Step 3 Perform Calculation: The program sums the five marks and divides the total by the
maximum possible score (e.g., total_marks / 500) to calculate the overall percentage.

Step 4 Assign Grade: The program uses conditional logic to assign a letter grade based on the
calculated percentage according to a predefined scale. For example:

If percentage is >= 90, assign 'A'

If percentage is >= 80 and < 90, assign 'B'

If percentage is >= 70 and < 80, assign 'C'

If percentage is >= 60 and < 70, assign 'D'

If percentage is < 60, assign 'F'

Step 5 Display Result: The program displays both the calculated percentage and the assigned
grade to the user.

Step 6 End the Program.

Program:
m1=int(input('Enter marks in sub 1:'))

m2=int(input('Enter marks in sub 2:'))

m3=int(input('Enter marks in sub 3:'))

avg=(m1+m2+m3)/m3

if avg<=90: grade='A'

elif avg<=80: grade='B'

elif avg<=70: grade='C'


elif avg<=60: grade='D'

elif avg<=50: grade='E'

else: grade='F'

print(grade)

print('Name: Vidushi Singh ')

print('Registration number: 25BCE10314')

Output
7.

Aim: To create an application that calculates both the simple and compound interest for a given
principal amount, interest rate, and time period, based on user input.

Algorithm:
Step 1 Start the Program: The application loads and presents the user interface.

Step 2 Get Input: The program prompts the user to enter three values:

Principal Amount (P)

Annual Interest Rate (R)

Time Period in Years (T)

Step 3 Perform Simple Interest Calculation: The program calculates the simple interest using
the formula:

SI=(P×R×T)/100Error! Filename not specified.

Step 4 Perform Compound Interest Calculation: The program calculates the compound interest
using the formula:

A=P(1+R/100)TError! Filename not specified.

CI=A−P where A is the final amount.

Step 5 Display Result: The program displays both the calculated Simple Interest (SI) and
Compound Interest (CI) to the user.

Step 6 End the Program.

Program :
P=float(input("Enter the principal amount: "))

R=float(input("Enter the rate of interest in percentage: "))

T=float(input("Enter the time period in years: "))

print("Simple interest= ",P*R*T/100)

print("compound interest= ",(P* ((1 + (R / 100 ))** T))-P)


Output:
8.

Aim: Determining if an input character is a vowel or a consonant.

Algorithm:
Step 1 Start the Program.

Step 2 Declare a variable to store the input character.

Step 3Prompt the user to enter a single character.

Step 4 Read the character entered by the user.

Step 5 Convert the character to a single case (e.g., lowercase) for consistent comparison.

Step 6 Check if the character is one of the vowels: 'a', 'e', 'i', 'o', or 'u'.

Step 7 If the character matches any of the vowels, print "The character is a vowel."

Otherwise (if the character is not a vowel), print "The character is a consonant."

Step 8 End the Program.

Program:
char=str(input("enter any letter: "))

if(char=='a' or char=='e' or char=='i' or char=='o' or char=='u'):

print("vowel")

else:

print("consonant")

print(“Vidushi Singh”)

print(“25BCE10314”)
Output:
9.

Aim: Using a for loop to find the sum of digits of a number entered by the user.

Algorithm:
Step 1 Start the Program.

Step 2 Declare a variable, inputNumber, to store the number entered by the user.

Step 3 Prompt the user to enter a number.

Step 4 Read the input value and store it in inputNumber.

Step 5 Convert inputNumber to a string to iterate through its digits.

Step 6 Initialize a variable, sumOfDigits, to 0. This variable will store the running sum.

Step 7 Start a for loop that iterates through each character (digit) of the string representation of
inputNumber.

Step 8 Inside the loop, convert the current character back to an integer.

Step 9 Add this integer to the sumOfDigits variable.

Step 10 Repeat steps 8 and 9 until the loop has completed.

Step 11 Print the final sumOfDigits.

Step 12 End the Program.

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

# Initialize sum

sum_of_digits = 0

# Loop to extract and add digits


while num > 0:

digit = num % 10 # Get the last digit

sum_of_digits += digit # Add digit to sum

num = num // 10 # Remove the last digit

print("Sum of digits is:", sum_of_digits)

print(“Vidushi Singh”)

print(“25BCE10314”)

Output
10.

Aim: Using a for loop to find the reverse of a number entered by the user.

Algorithm:
Step 1 Start the Program.

Step 2 Declare a variable, inputNumber, to store the number entered by the user.

Step 3 Prompt the user to enter a number.

Step 4 Read the input value and store it in inputNumber.

Step 5Convert inputNumber to a string.

Step 6 Initialize an empty string variable, reversedString.

Step 7 Start a for loop that iterates from the last character of the inputNumber string to the
first.

Step 8 Inside the loop, append each character to the reversedString.

Step 9After the loop, convert the reversedString back to an integer.

Step 10 Print the final reversed number.

Step 11End the Program

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

# Initialize reversed number to 0

reversed_num = 0

# Loop to reverse the number

while num > 0:


digit = num % 10 # Get the last digit

reversed_num = reversed_num * 10 + digit # Append digit to reversed number

num = num // 10 # Remove the last digit

# Output the result

print("Reversed number is:", reversed_num)

Output:
11.

Aim: Using a for loop to find if a number is prime or not.

Algorithm:
1. Start the Program.

2. Declare a variable, inputNumber, to store the number entered by the user.

3. Prompt the user to enter a number.

4. Read the input value and store it in inputNumber.

5. Check if inputNumber is less than or equal to 1. If it is, print that the number is not a
prime number and end the program.

6. Initialize a boolean variable, isPrime, to true.

7. Start a for loop that iterates from i = 2 up to inputNumber - 1.

8. Inside the loop, check if the remainder of inputNumber divided by i is 0 (i.e.,


inputNumber % i == 0).

9. If the remainder is 0, it means inputNumber is divisible by i, and therefore not a prime


number.

10. If the number is not prime, set isPrime to false.

11. Break the loop immediately, as there is no need to check further.

12. After the loop, check the value of isPrime.

13. If isPrime is true, print that the number is prime.

14. If isPrime is false, print that the number is not prime.

15. End the Program.

Program
num = int(input("Enter a number: "))
# Check if number is less than or equal to 1

if num <= 1:

print(num, "is not a prime number")

else:

# Assume number is prime until proven otherwise

is_prime = True

# Use a for loop to check for factors

for i in range(2, num):

if num % i == 0:

is_prime = False

break # Exit loop if a factor is found

# Output result

if is_prime:

print(num, "is a prime number")

else:

print(num, "is not a prime number")

Output:
12.

Aim: Using a for loop to find if a number is an Armstrong number.

Algorithm:
1. Start the Program.

2. Declare a variable, inputNumber, to store the number entered by the user.

3. Prompt the user to enter a number.

4. Read the input value and store it in inputNumber.

5. Create a temporary variable, originalNumber, and assign it the value of inputNumber.

6. Convert inputNumber to a string to find the number of digits. Let's call this string
numString.

7. Initialize a variable, sumOfCubes, to 0. This variable will store the sum of the cubes of
the digits.

8. Start a for loop that iterates through each character (digit) of the numString.

9. Inside the loop, convert the current character back to an integer.

10. Calculate the cube of the digit and add it to sumOfCubes.

11. After the loop, compare sumOfCubes with the originalNumber.

12. If sumOfCubes is equal to originalNumber, print that the number is an Armstrong


number.

13. Otherwise, print that the number is not an Armstrong number.

14. End the Program.

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

# Store the original number for comparison later


original_num = num

# Count the number of digits

num_digits = len(str(num))

# Initialize sum of powers

sum_of_powers = 0

# Use a loop to extract each digit and add its power

while num > 0:

digit = num % 10

sum_of_powers += digit ** num_digits

num = num // 10 # Remove the last digit

# Check if it is an Armstrong number

if sum_of_powers == original_num:

print(original_num, "is an Armstrong number")

else:

print(original_num, "is not an Armstrong number")

Output :
13.

Aim: Using a for loop to find the sum of 'n' numbers.

Algorithm:
1. Start the Program.

2. Declare a variable, n, to store the number of terms for the sum.

3. Prompt the user to enter a positive integer for n.

4. Read the input value and store it in n.

5. Initialize a variable, totalSum, to 0.

6. Start a for loop that iterates from i = 1 up to n.

7. Inside the loop, add the value of i to totalSum.

8. After the loop, print the value of totalSum.

9. End the Program.

Program
n = int(input("Enter how many numbers you want to sum: "))

# Initialize total sum

total = 0

# Loop to get each number and add to total

for i in range(n):

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

total += num
# Output the result

print("The sum of", n, "numbers is:", total)

Output:
14.

Aim: Using a for loop to find the maximum and minimum of 5 numbers entered by the user.

Algorithm:
1. Start the Program.

2. Declare a variable, inputNumber, to store the number entered by the user.

3. Declare two variables, maxNumber and minNumber, and initialize both to the first number
entered by the user.

4. Prompt the user to enter five numbers.

5. Read the first number entered by the user and store it in inputNumber.

6. Set maxNumber and minNumber to the value of inputNumber.

7. Start a for loop that iterates from i = 1 up to 4 (since the first number has already been
processed).

8. Inside the loop, prompt the user to enter a number.

9. Read the number and store it in inputNumber.

10. Check if inputNumber is greater than maxNumber. If it is, update maxNumber with the
value of inputNumber.

Check if inputNumber is less than minNumber. If it is, update minNumber with the value of
inputNumber.

11. After the loop, print the value of maxNumber as the maximum number.

12. Print the value of minNumber as the minimum number.

End the Program.

Program
# Check for valid input

if n <= 0:
print("Please enter a number greater than 0.")

else:

# Input the first number to initialize max and min

first = float(input("Enter number 1: "))

max_num = first

min_num = first

# Loop to read remaining numbers and compare

for i in range(1, n):

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

if num > max_num:

max_num = num

if num < min_num:

min_num = num

# Output the results

print("Maximum number is:", max_num)

print("Minimum number is:", min_num)

Output
15.

Aim: Using a for loop to find the second maximum and second minimum of 5 numbers entered
by the user.

Algorithm:
1. Start the Program.

2. Declare a variable, inputNumber, to store the number entered by the user.

3. Declare two variables for the maximum values: firstMax and secondMax. Initialize
them to a very small number (e.g., a large negative number).

4. Declare two variables for the minimum values: firstMin and secondMin. Initialize them
to a very large number (e.g., a large positive number).

5. Start a for loop that iterates five times (e.g., i = 1 to 5).

6. Inside the loop, prompt the user to enter a number.

7. Read the number and store it in inputNumber.

Finding Maximums:

If inputNumber is greater than firstMax:

Set secondMax to the value of firstMax.

Set firstMax to the value of inputNumber.

Else if inputNumber is greater than secondMax and inputNumber is not equal to firstMax:

Set secondMax to the value of inputNumber.

Finding Minimums:

If inputNumber is less than firstMin:

Set secondMin to the value of firstMin.

Set firstMin to the value of inputNumber.

Else if inputNumber is less than secondMin and inputNumber is not equal to firstMin:

Set secondMin to the value of inputNumber.


8. After the loop, print the value of secondMax as the second maximum number.

9. Print the value of secondMin as the second minimum number.

10. End the Program.

Program:
n = int(input("Enter how many numbers: "))

if n < 2:

print("Please enter at least two numbers.")

else:

numbers = []

for i in range(n):

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

[Link](num)

# Remove duplicates to handle cases where max and second max might be same

unique_numbers = list(set(numbers))

if len(unique_numbers) < 2:

print("Not enough unique numbers to find 2nd max and 2nd min.")

else:

unique_numbers.sort()

second_min = unique_numbers[1]

second_max = unique_numbers[-2]
print("Second minimum number is:", second_min)

print("Second maximum number is:", second_max)

Program:
16.

AIM: To find the roots of quadratic equations

ALGORITHM:

[Link] the procedure

[Link] input from user

[Link] discriminant and classify type of roots

[Link] roots using quadratic formula

[Link] output

6. End procedure

Program
a=int(input('Enter coefficient of x^2:'))

b=int(input('Enter coefficient of x:'))

c=int(input('Enter constant:'))

D=b**2-4*a*c

if D>0:

print('Roots are real')

r1=D-b/2*a

print(r1,'is the root')

elif D<0 : print(‘Roots are imaginary ’)

else:

r1=-b/2*a

print(r1,’is the root’)


print(‘Name:Vidushi SIngh’)

print(‘Registration number : 25BCE10314’)

Output:
17.

AIM: To write a Python program to generate prime numbers between two given
numbers.

ALGORITHM:
[Link] the procedure

[Link] input from user

[Link] each number for [Link] prime

[Link] output

5. End procedure

Program:
start = int(input("Enter start: "))

end = int(input("Enter end: "))

for num in range(start, end+1):

if num > 1:

for i in range(2, num):

if num % i == 0:

break

else:

print(num)
Output
18.
AIM: To write a Python program to find sum of even and odd numbers separately
ALGORITHM:
[Link] the procedure

[Link] input from user for n

[Link] even numbers separately and odd numbers separately

[Link] output

5. End procedure

Program:
n = int(input("Enter how many numbers: "))

se = so = 0

for i in range(n):

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

if val % 2 == 0:

se += val

else:

so += val

print("Sum of even numbers:", se)

print("Sum of odd numbers:", so)


Output:
19.

AIM: To write a Phyton Code to display multiplication table of given


number
ALGORITHM:
[Link] the procedure
[Link] input from user
[Link] loop from 1 to 10 and multiply number with loop counter
[Link] output
5. End procedure

PROGRAM:
num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num*i)

OUTPUT;

:
20.

AIM: To classify input as character or integer


ALGORITHM:
[Link] the procedure
[Link] input from user
[Link] type of input using ‘in’ operator
[Link] output
5. End procedure

PROGRAM:
s=input('Enter input:')
if s in '1234567890':
print('Input is integer')
else: print('Input is character')

OUTPUT:
21.

AIM: Algorithm to generate the Fibonacci Series up to N terms:


ALGORITHM:
1. START
2. Declare integer variables: N (the number of terms to generate), a, b, c, and
an iteration counter i.
3. Take the desired number of terms, N, as input.
4. Initialize the first two Fibonacci terms: Set a = 0 and b = 1.
5. Print the first two terms: Print the values of a and b.
6. Start a loop for the remaining terms, initializing i = 3 and continuing while i
≤ N.
7. Inside the loop, calculate the next term: Set c = a + b.
8. Print the value of c.
9. Update the preceding terms for the next iteration: Set a = b and then b = c.
[Link] the counter: Set i = i + 1.
[Link] the loop.
[Link]

PROGRAM:
fib=int(input("enter the number of elements u want: "))

a=0

b=1

print(a)

print(b)

for i in range(2,fib):

c=a+b

a=b
b=c

print(c)

OUTPUT:

2.

AIM: Algorithm to calculate the factorial of a non-negative integer N:


ALGORITHM:
1. START
2. Declare integer variables: N (the number whose factorial is to be found),
Fact (to store the result), and an iteration counter i.
3. Take the non-negative integer N as input.
4. Initialize the result variable: Set Fact = 1.
5. Check for the base case (Factorial of 0 or 1 is 1): If N ≤ 1, skip to step 9.
6. Start a loop, initializing i = 1 and continuing while i ≤ N.
7. Inside the loop, multiply Fact by the current iteration number: Set Fact ←
Fact × i.
8. Increment the counter: Set i = i + 1.
9. End the loop.
[Link] the value of the variable Fact (the calculated factorial).
[Link]

PROGRAM:
num=int(input("enter the number of elements u want: "))
fact=1
for i in range(1,num+1):
fact=fact*i
print("factorial of",num,"is",fact)

OUTPUT:

3.

AIM: Algorithm to check if an input string S is a Palindrome:


Algorithm:
1. START
2. Declare variables: S (String input), Length (Integer), i (Integer, pointer from
start), j (Integer, pointer from end), and IsPalindrome (Boolean flag).
3. Take the string S as input.
4. Calculate the length of the string: Set Length ← length of S.
5. Initialize two pointers to the ends of the string: Set i ← 0 and j ← Length - 1.
6. Initialize the flag assuming it is a palindrome: Set IsPalindrome ← TRUE.
7. Start a loop while i < j.
8. Compare the character at position i with the character at position j.
9. If character at S[i] = character at S[j]: a. Set IsPalindrome ← FALSE. b.
Break the loop (jump to step 12).
[Link] the pointers inward: i ← i + 1 and j ← j - 1.
[Link] the loop.
[Link] IsPalindrome is TRUE, print "The string is a palindrome."
[Link] (if IsPalindrome is FALSE), print "The string is NOT a palindrome."
[Link]

PROGRAM:
str=input("Enter a string: ")
if str==str[::-1]:
print("it is a palindrome")
else:
print("it is not a palindrome")

OUTPUT:
4.
Aim:Algorithm on function swapping without and with temporary variable

Algorithm:
1. Start
2. Declare three variables: a (first number), b (second number), and temp
(temporary variable).

3. Take the two numbers a and b as input.

4. Store the value of a into the temporary variable: temp ← a.

5. Assign the value of b to a: a ← b.

6. Assign the value of temp to b: b ← temp.

7. At this point, the values of a and b are swapped.

8. Print the new values of a and b.

9. End

Program:
def swap_with_temp(a, b):
print("Before swapping (with temp): a =", a, " b =", b)
temp = a
a=b
b = temp
print("After swapping (with temp): a =", a, " b =", b)
return a, b
def swap_without_temp(a, b):
print("Before swapping (without temp): a =", a, " b =", b)
a=a+b
b=a-b
a=a-b
print("After swapping (without temp): a =", a, " b =", b)
return a, b
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
swap_with_temp(x, y)
swap_without_temp(x, y)
print("Vidushi Singh")
print("25BCE10314")

OUTPUT:

5.

AIM:Base conversion Binary to decimal


ALGORITHM:
1. START
2. Take a binary number as input. This number will only have digits 0 and 1.
3. Find the length of the binary number.
4. Set a variable Decimal equal to 0. This will store the final answer.
5. Go through each digit of the binary number one by one from left to right.
o Each time, take the digit.
o Multiply the current value of Decimal by 2 and then add this digit to it.
6. Keep repeating the above step until all digits are covered.
7. After the loop ends, the value stored in Decimal will be the decimal form of the given
binary number.
8. Print the value of Decimal.
9. END

PROGRAM-
binary = input("Enter a binary number: ")
decimal = 0
for digit in binary:
decimal = decimal * 2 + int(digit)
print("The decimal value is:", decimal)

print("Vidushi Singh")
print("25BCE10314")

OUTPUT:
26) To print the last digit of a number.

Algorithm

Step 1 : Start the process.

Step 2: Define a function to exract the last digit of the number by using (number %10)

and then return the last digit.

Step 3: Ask the user to enter the number.

Step 4 : Print the last digit of the number by calling the function.
Step 5: Stop the process.

Code

def last_digit(n):

return n%10

n=int(input("Enter the number:-"))

print(last_digit(n))

print("Registration number: 25BCE10314")

print("Name: Vidushi Singh")

Output:

27) To print the sum of last digit of two numbers.

Algorithm:

Step 1: Start the process.

Step 2: Ask the user to enter any two numbers.

Step 3: Extract the last digit of both the number using n%10.

Step 4: Add both the digits and print the sum .

Step 5: Stop the process.


Code:

def last_digit(n):

return n%10

n=int(input("Enter the number:-"))

m=int(input("Enter the second number:-"))

print(last_digit(n)+last_digit(m))

print("Registration number:-25BCE10314")

print("Name:Vidushi Singh”)

OUTPUT:

28) To print the sum of array elements.

Algorithm:

Step1: Start the process.

Step 2: Define a function that return the sum of all the elements of an array entered.

Step 3:Call the function and print the sum.

Step 4: Stop the process.

Code:
def sum_of_array(arr):

return sum(arr)

array = [1, 2, 3, 4, 5]

result = sum_of_array(array)

print("Sum of array elements:", result)

print("Registration number:-25BCE10314")

print("Name:Vidushi Singh”)

Output:

29) Program to sort an array in ascending or descending order without using


functions.

Algorithm:

Step 1: Start with the first element of the array.

Step 2: Compare it with the next element.

Step 3: Swap the elements if they are not in the desired order (ascending or descending).

Step 4: Repeat this process for all elements, reducing the range of comparison after each pass.

Step 5: Continue until the array is fully sorted.


Step 6: Stop the process.

Program code:

def sort_array(arr, order="ascending"):

n = len(arr)

for i in range(n):

for j in range(0, n - i - 1):

if (order == "ascending" and arr[j] > arr[j + 1]) or (order == "descending" and arr[j] < arr[j +
1]):

# Swap elements

arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Input array

array = [34, 7, 23, 32, 5, 62]

# Sorting in ascending order

sort_array(array, order="ascending")

print("Ascending Order:", array)

# Sorting in descending order

sort_array(array, order="descending")

print("Descending Order:", array)

print("Registration number:-25BCE10314")

print("Name:Vidushi Singh”)

Output:
30) To print the kth smallest and largest element from an array.

Algorithm:

Input: An array arr and an integer k.

Sort the array in ascending order.

K-th Smallest: The element at index k-1 in the sorted array.

K-th Largest: The element at index -k in the sorted array.


Output: Return both the k-th smallest and k-th largest elements.

Program code:

def find_kth_smallest_largest(arr, k):

# Sort the array

[Link]()

# k-th smallest element

kth_smallest = arr[k - 1]

# k-th largest element

kth_largest = arr[-k]

return kth_smallest, kth_largest

# Example usage

array = [7, 10, 4, 3, 20, 15]

k=3

kth_smallest, kth_largest = find_kth_smallest_largest(array, k)

print(f"The {k}rd smallest element is {kth_smallest}")

print(f"The {k}rd largest element is {kth_largest}")

print("Registration number:-25BCE10314")

print("Name:Vidushi Singh”)
Output:

31.)
Aim: Finding a perfect Square Root – using prime

Factorization

Algorithm:

Finding a Square Root by Prime Factorization


Step 1- Obtain the given number

Step 2- Write the Prime Factors in pairs.

Step 3- Group the Prime Factors in Pairs.

Step 4-Write the numbers as square root of prime factors.

Step 5- Take one factor from each pair

Step 6- Find the product of factors obtained in Step 5.

Step 7-The product obtained in Step 6 is the required square root.


CODE: def prime_factors(n):
factors = []

divisor = 2

while n > 1:

while n % divisor == 0:

[Link](divisor)

n //= divisor

divisor += 1

return factors

def perfect_square_root(n):

factors = prime_factors(n)

factor_count = {}

# Count occurrences of each factor

for factor in factors:

factor_count[factor] = factor_count.get(factor, 0) + 1

# Check if all factors have even powers

root = 1

for factor, count in factor_count.items():

if count % 2 != 0:

return None # Not a perfect square

root *= factor ** (count // 2)


return root

# Example usage

number = int(input("Enter the number"))

result = perfect_square_root(number)

if result:

print(f"The square root of {number} is {result}.")

else:

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

print("Registration number:-25BCE10314")

print("Name:Vidushi Singh”)

OUTPUT:
32)
Perfect square root by using python in-built functions.
Algorithm:
1. Start.
2. Import the math module.
3. Read an integer n from the user.
4. If n < 0: a. Print an error message (e.g., "Please enter a non-negative number.").

5. Else: a. Calculate the square root: root = [Link](n).


b. Check if root is a whole number (e.g., if root == int(root):).
c. If true: i. Print int(root) as the perfect square root.

d. If false: i. Print that n is "not a perfect square."

6. End.
CODE:
import math
number = int(input("enter a number"))
square_root = [Link](number)
print(f"The square root of {number} is: {square_root}")
print("Vidushi Singh")
print("25BCE10314")
OUTPUT:
33).
Aim:
Finding the Smallest divisor using Factoring Method
Algorithm:
1. Start.
2. Read a positive integer n from the user.
3. If n <= 1, print an error (e.g., "Please enter a number greater than 1.") and stop.
4. If n % 2 == 0 (is even), print 2 and stop.
5. Initialize a variable i = 3.
6. Start a loop that continues as long as i * i <= n.
7. Inside the loop: a. If n % i == 0 (i is a divisor), print i and stop.
b. Increment i by 2 (to check only odd numbers).

8. If the loop finishes without stopping, print n (because the number is prime).
9. End.

CODE:
def smallest_divisor(n):

if n <= 1:

return n

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

return i

return n

number = 56

print(f"The smallest divisor of {number} is {smallest_divisor(number)}")

print("Vidushi Singh")
print("25BCE10314")
OUTPUT:
34). ) To Generate Prime Factors Of A Number.

Algorithm:

Step 1: Input Validation

Ensure the number is an integer greater than 1 (since prime factors are defined for integers > 1).

Step 2: Divide by 2 until odd

While the number is divisible by 2, store 2 as a prime factor and divide the number by 2.

Step 3: Check odd factors

Step 4: Start from 3 and check divisibility up to the square root of the number.

For each odd number i, while divisible, store i as a prime factor and divide.

Remaining prime

Step 5: If after the loop the number is greater than 2, it is itself a prime factor.

Step 6: Return or print the list of prime factors.

Program code:

def prime_factors(n):

factors = []

while n % 2 == 0:

[Link](2)

n //= 2

for i in range(3, int(n**0.5) + 1, 2):

while n % i == 0:

[Link](i)

n //= i
if n > 2:

[Link](n)

return factors

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

print(f"Prime factors of {number} are: {prime_factors(number)}")

print("Vidushi Singh")
print("25BCE10314")

OUTPUT:

35) To find the greatest common divisor.


Algorithm:

Step 1: Start

Step 2: Input two integers a and b.

Step 3: Convert both numbers to their absolute values (GCD is always positive).

Repeat until b becomes 0:

Step 4: Store b in a temporary variable temp.

Step 5: Set b to a % b (remainder of a divided by b).

Set a to temp.

When b becomes 0, a contains the GCD.

Step 6: Output a as the GCD.

Step 7: End

Program code:

def gcd_recursive(a, b):

if b == 0:

return a

return gcd_recursive(b, a % b)

# Input two numbers

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

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

# Calculate GCD

gcd = gcd_recursive(num1, num2)


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

print("Vidushi Singh")
print("25BCE10314")

OUTPUT:

You might also like