Basic Algorithms and Programs in Python
Basic Algorithms and Programs in Python
1.
Algorithm:
Step 1: Start the process
Step 3: Check whether 'a' is divisible by 2 and the remainder is zero then display as 'even number'
otherwise display as 'odd number'
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.
Algorithm:
Step 1: Start the process
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'.
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.
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
Area=π×radius2
Area=length×width
Area=side2
Area=21×base×height
Use a break statement to exit the loop and end the program.
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"):
print(side*side)
elif(shape=="circle"):
print(3.14*rad) elif(shape=="rectangle"):
print(“Vidushi Singh”)
print(“25BCE10314”)
Output:
4.
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:
Program Code:
type=str(input("choose the operation u want to perform +,-,/,* : "))
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.
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.
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.
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"):
elif(type=="2"):
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:
Step 5 Display Result: The program displays both the calculated percentage and the assigned
grade to the user.
Program:
m1=int(input('Enter marks in sub 1:'))
avg=(m1+m2+m3)/m3
if avg<=90: grade='A'
else: grade='F'
print(grade)
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:
Step 3 Perform Simple Interest Calculation: The program calculates the simple interest using
the formula:
Step 4 Perform Compound Interest Calculation: The program calculates the compound interest
using the formula:
Step 5 Display Result: The program displays both the calculated Simple Interest (SI) and
Compound Interest (CI) to the user.
Program :
P=float(input("Enter the principal amount: "))
Algorithm:
Step 1 Start the Program.
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."
Program:
char=str(input("enter any letter: "))
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 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.
Program
num = int(input("Enter a number: "))
# Initialize sum
sum_of_digits = 0
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 7 Start a for loop that iterates from the last character of the inputNumber string to the
first.
Program
num = int(input("Enter a number: "))
reversed_num = 0
Output:
11.
Algorithm:
1. Start the Program.
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.
Program
num = int(input("Enter a number: "))
# Check if number is less than or equal to 1
if num <= 1:
else:
is_prime = True
if num % i == 0:
is_prime = False
# Output result
if is_prime:
else:
Output:
12.
Algorithm:
1. Start the Program.
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.
Program
num = int(input("Enter a number: "))
num_digits = len(str(num))
sum_of_powers = 0
digit = num % 10
if sum_of_powers == original_num:
else:
Output :
13.
Algorithm:
1. Start the Program.
Program
n = int(input("Enter how many numbers you want to sum: "))
total = 0
for i in range(n):
total += num
# Output the result
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.
3. Declare two variables, maxNumber and minNumber, and initialize both to the first number
entered by the user.
5. Read the first number entered by the user and store it in inputNumber.
7. Start a for loop that iterates from i = 1 up to 4 (since the first number has already been
processed).
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.
Program
# Check for valid input
if n <= 0:
print("Please enter a number greater than 0.")
else:
max_num = first
min_num = first
max_num = num
min_num = 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.
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).
Finding Maximums:
Else if inputNumber is greater than secondMax and inputNumber is not equal to firstMax:
Finding Minimums:
Else if inputNumber is less than secondMin and inputNumber is not equal to firstMin:
Program:
n = int(input("Enter how many numbers: "))
if n < 2:
else:
numbers = []
for i in range(n):
[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)
Program:
16.
ALGORITHM:
[Link] output
6. End procedure
Program
a=int(input('Enter coefficient of x^2:'))
c=int(input('Enter constant:'))
D=b**2-4*a*c
if D>0:
r1=D-b/2*a
else:
r1=-b/2*a
Output:
17.
AIM: To write a Python program to generate prime numbers between two given
numbers.
ALGORITHM:
[Link] the procedure
[Link] output
5. End procedure
Program:
start = int(input("Enter start: "))
if num > 1:
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] output
5. End procedure
Program:
n = int(input("Enter how many numbers: "))
se = so = 0
for i in range(n):
if val % 2 == 0:
se += val
else:
so += val
PROGRAM:
num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num*i)
OUTPUT;
:
20.
PROGRAM:
s=input('Enter input:')
if s in '1234567890':
print('Input is integer')
else: print('Input is character')
OUTPUT:
21.
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.
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.
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).
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.
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 2: Define a function to exract the last digit of the number by using (number %10)
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
print(last_digit(n))
Output:
Algorithm:
Step 3: Extract the last digit of both the number using n%10.
def last_digit(n):
return n%10
print(last_digit(n)+last_digit(m))
print("Registration number:-25BCE10314")
print("Name:Vidushi Singh”)
OUTPUT:
Algorithm:
Step 2: Define a function that return the sum of all the elements of an array entered.
Code:
def sum_of_array(arr):
return sum(arr)
array = [1, 2, 3, 4, 5]
result = sum_of_array(array)
print("Registration number:-25BCE10314")
print("Name:Vidushi Singh”)
Output:
Algorithm:
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.
Program code:
n = len(arr)
for i in range(n):
if (order == "ascending" and arr[j] > arr[j + 1]) or (order == "descending" and arr[j] < arr[j +
1]):
# Swap elements
# Input array
sort_array(array, order="ascending")
sort_array(array, order="descending")
print("Registration number:-25BCE10314")
print("Name:Vidushi Singh”)
Output:
30) To print the kth smallest and largest element from an array.
Algorithm:
Program code:
[Link]()
kth_smallest = arr[k - 1]
kth_largest = arr[-k]
# Example usage
k=3
print("Registration number:-25BCE10314")
print("Name:Vidushi Singh”)
Output:
31.)
Aim: Finding a perfect Square Root – using prime
Factorization
Algorithm:
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 = {}
factor_count[factor] = factor_count.get(factor, 0) + 1
root = 1
if count % 2 != 0:
# Example usage
result = perfect_square_root(number)
if result:
else:
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.").
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
if n % i == 0:
return i
return n
number = 56
print("Vidushi Singh")
print("25BCE10314")
OUTPUT:
34). ) To Generate Prime Factors Of A Number.
Algorithm:
Ensure the number is an integer greater than 1 (since prime factors are defined for integers > 1).
While the number is divisible by 2, store 2 as a prime factor and divide the number by 2.
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.
Program code:
def prime_factors(n):
factors = []
while n % 2 == 0:
[Link](2)
n //= 2
while n % i == 0:
[Link](i)
n //= i
if n > 2:
[Link](n)
return factors
print("Vidushi Singh")
print("25BCE10314")
OUTPUT:
Step 1: Start
Step 3: Convert both numbers to their absolute values (GCD is always positive).
Set a to temp.
Step 7: End
Program code:
if b == 0:
return a
return gcd_recursive(b, a % b)
# Calculate GCD
print("Vidushi Singh")
print("25BCE10314")
OUTPUT: