0% found this document useful (0 votes)
16 views295 pages

C and Python Programs for Number Algorithms

The document provides various programming examples in C and Python, including reversing a number, generating Fibonacci series, finding the GCD, checking for perfect numbers, and determining if two strings are anagrams. Each example includes code snippets, explanations of the algorithms used, and example outputs. The document serves as a comprehensive guide for implementing these algorithms in both programming languages.

Uploaded by

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

C and Python Programs for Number Algorithms

The document provides various programming examples in C and Python, including reversing a number, generating Fibonacci series, finding the GCD, checking for perfect numbers, and determining if two strings are anagrams. Each example includes code snippets, explanations of the algorithms used, and example outputs. The document serves as a comprehensive guide for implementing these algorithms in both programming languages.

Uploaded by

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

1.

​C Program: Reverse a Number


#include <stdio.h> // Include standard input-output library for
printf and scanf

int main() {

int num, reversed = 0, remainder;

// Ask user to enter a number

printf("Enter an integer: ");

scanf("%d", &num); // Read integer input from user

// Logic: Extract last digit and build reversed number

while (num != 0) {

remainder = num % 10; // Get last digit using modulus

reversed = reversed * 10 + remainder; // Append digit to


reversed number

num = num / 10; // Remove last digit from


original number

// Print the reversed number

printf("Reversed number: %d\n", reversed);

return 0; // Exit the program successfully

}
Explanation:

●​ % gives the last digit of the number.​

●​ reversed * 10 shifts existing digits left by one place (like adding a new digit).​

●​ + remainder adds the last extracted digit.​

●​ /10 removes the last digit from the original number.​

●​ The loop continues until all digits are processed.​

Example walkthrough:​
If input = 1234

●​ Step 1: remainder = 4 → reversed = 0*10+4 = 4​

●​ Step 2: remainder = 3 → reversed = 4*10+3 = 43​

●​ Step 3: remainder = 2 → reversed = 43*10+2 = 432​

●​ Step 4: remainder = 1 → reversed = 432*10+1 = 4321​

Output: 4321 ✅
Python Program: Reverse a Number
# Ask user for input

num = int(input("Enter an integer: ")) # Convert input string to


integer

# Initialize reversed number to 0

reversed_num = 0

# Use a temporary variable since we'll modify num

temp = num
# Loop until the number becomes 0

while temp != 0:

remainder = temp % 10 # Extract last digit

reversed_num = reversed_num * 10 + remainder # Append digit to


reversed number

temp = temp // 10 # Remove last digit using


integer division

# Display the result

print("Reversed number:", reversed_num)

Explanation:

●​ input() gets user input as a string; we convert it to integer using int().​

●​ % 10 → extracts last digit​

●​ // 10 → removes last digit (integer division)​

●​ We multiply reversed_num by 10 each step to shift digits left and append new digit.​

Example:

Input: 5678

Step 1: remainder = 8 → reversed_num = 0*10+8 = 8

Step 2: remainder = 7 → reversed_num = 8*10+7 = 87

Step 3: remainder = 6 → reversed_num = 87*10+6 = 876

Step 4: remainder = 5 → reversed_num = 876*10+5 = 8765

Output: 8765
Alternative Python Trick (Short Version)
If you want a one-line logic using string slicing:

num = input("Enter an integer: ")

print("Reversed number:", num[::-1])

🔹 [::-1] → Python slicing technique to reverse a string​


🔹 But note: This treats number as string, not actual integer.

2. C Program: Fibonacci Series


#include <stdio.h> // Include standard I/O library for printf and
scanf

int main() {

int n, first = 0, second = 1, next, i;

// Ask the user to enter how many terms to print

printf("Enter the number of terms: ");

scanf("%d", &n); // Read the input number of terms

// Check if the user entered a valid number

if (n <= 0) {

printf("Please enter a positive integer.\n");

return 0; // Exit the program


}

printf("Fibonacci Series: ");

// Print the first two terms manually if n >= 1

for (i = 1; i <= n; i++) {

if (i == 1) {

printf("%d ", first); // First term is 0

continue;

if (i == 2) {

printf("%d ", second); // Second term is 1

continue;

// Calculate the next term

next = first + second; // Next term is the sum of previous


two

printf("%d ", next); // Print the next term

// Update the previous two terms

first = second; // Shift second to first

second = next; // Shift next to second

}
printf("\n"); // New line after printing the series

return 0; // Exit successfully

Logic Explanation (C Program):

●​ Fibonacci series starts with 0, 1​

●​ Each next term = sum of previous two terms​

Use a loop to generate terms:​



next = first + second

first = second

second = next

●​
●​ Repeat n times.​

Example:​
For n = 6 →​
0 (first), 1 (second),​
2 (0+1), 3 (1+2), 5 (2+3), 8 (3+5)

Output: 0 1 1 2 3 5

Python Program: Fibonacci Series


# Ask the user to enter number of terms

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

# Initialize first two terms of Fibonacci series

first, second = 0, 1
# Check for invalid input

if n <= 0:

print("Please enter a positive integer.")

else:

print("Fibonacci Series:")

# Loop through n times

for i in range(1, n + 1):

if i == 1:

print(first, end=" ") # Print first term

continue

if i == 2:

print(second, end=" ") # Print second term

continue

# Calculate next term

next_term = first + second

print(next_term, end=" ") # Print the next term

# Update previous two terms

first = second

second = next_term
print() # Print new line after the series

Logic Explanation (Python Program):

●​ Base terms: 0, 1​

●​ For each iteration:​

○​ Compute next_term = first + second​

○​ Print next_term​

○​ Shift first → second, and second → next_term​

●​ Repeat for n terms​

Example:​
Input: n = 7​
Output: 0 1 1 2 3 5 8

Bonus: Python (Simple List Version)


If you want to store Fibonacci numbers in a list:

n = int(input("Enter number of terms: "))

fib_series = [0, 1]

for i in range(2, n):

fib_series.append(fib_series[i-1] + fib_series[i-2])

print("Fibonacci Series:", fib_series[:n])

3. GCD (Greatest Common Divisor) Program

What is GCD?
The GCD (Greatest Common Divisor) of two integers is the largest positive integer that
divides both numbers without leaving a remainder.

For example:​
GCD of 36 and 60 is 12​
Because 12 divides both 36 and 60 exactly.

Understanding the Algorithm (Euclidean Algorithm)


We use the Euclidean Algorithm to find the GCD efficiently.

Step-by-Step Explanation:

1.​ Suppose we have two numbers a and b.​

2.​ Divide a by b and find the remainder.​

3.​ Replace a with b, and b with the remainder.​

4.​ Repeat this process until b becomes 0.​

5.​ When b becomes 0, the current value of a is the GCD.​

Example:

Find GCD of 36 and 60​


a = 60, b = 36​
→ 60 % 36 = 24​
→ 36 % 24 = 12​
→ 24 % 12 = 0​
So, GCD = 12

C Program: Find GCD of Two Numbers


#include <stdio.h>

int main() {

int num1, num2, a, b, remainder, gcd;


printf("Enter two positive integers: ");

scanf("%d %d", &num1, &num2);

// Copy input values so that original numbers are not changed

a = num1;

b = num2;

// Repeat the process until remainder becomes 0

while (b != 0) {

remainder = a % b; // Find remainder

a = b; // Move b to a

b = remainder; // Move remainder to b

// When b becomes 0, a will hold the GCD

gcd = a;

printf("GCD of %d and %d is %d\n", num1, num2, gcd);

return 0;

Explanation:
●​ We read two numbers.​

●​ Then apply the Euclidean algorithm using a loop.​

●​ When b becomes 0, a contains the GCD.​

●​ Print the result.​

Python Program: Find GCD of Two


Numbers
# Input two positive integers from user

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

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

# Copy values to temporary variables

a = num1

b = num2

# Apply Euclidean Algorithm

while b != 0:

remainder = a % b # Find remainder

a = b # Replace a with b

b = remainder # Replace b with remainder

# When b becomes 0, a is the GCD

gcd = a
print("GCD of", num1, "and", num2, "is", gcd)

Explanation:

●​ The same logic is used as in C.​

●​ The loop continues until the remainder becomes 0.​

●​ The final value of a is printed as the GCD.​

Summary
Ste Operation Explanation
p

1 remainder = a % Divide a by b to find remainder


b

2 a=b Move b to a

3 b = remainder Move remainder to b

4 Repeat until b = 0 Stop when b becomes zero

5 Result: GCD = a The last non-zero a is the GCD

Bonus: Python Shortcut (Built-in Function)


Python provides a built-in function in the math module:
import math

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

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

print("GCD is:", [Link](num1, num2))

4. What is a Perfect Number?


A Perfect Number is a positive integer that is equal to the sum of its proper divisors
(excluding the number itself).

Example:

Take 6​
Divisors of 6 = 1, 2, 3 (excluding 6)​
Sum = 1 + 2 + 3 = 6​
So, 6 is a Perfect Number

Another example: 28​


Divisors = 1, 2, 4, 7, 14​
Sum = 1 + 2 + 4 + 7 + 14 = 28​
So, 28 is also a Perfect Number

Algorithm (Step-by-Step)
1.​ Input a number n​

2.​ Initialize sum = 0​

3.​ Loop through all numbers from 1 to n/2 (no need to check beyond half)​

4.​ For each number i, if n % i == 0, then add i to sum​

5.​ After the loop ends, compare:​


○​ If sum == n, then it is a Perfect Number​

○​ Otherwise, it is not​

C Program: Check Perfect Number


#include <stdio.h>

int main() {

int n, i, sum = 0;

// Step 1: Take input from user

printf("Enter a positive integer: ");

scanf("%d", &n);

// Step 2: Check for all divisors from 1 to n/2

for (i = 1; i <= n / 2; i++) {

if (n % i == 0) { // Step 3: Check if i is a divisor

sum = sum + i; // Step 4: Add divisor to sum

// Step 5: Compare sum with original number

if (sum == n) {

printf("%d is a Perfect Number.\n", n);


} else {

printf("%d is not a Perfect Number.\n", n);

return 0;

Explanation:

●​ Loop goes from 1 to n/2 because a number cannot have a divisor greater than its
half (except itself).​

●​ Sum up all divisors.​

●​ Compare the sum with n.​

Example:​
If n = 6​


Divisors: 1, 2, 3​
Sum = 6 → Perfect Number

Python Program: Check Perfect Number


# Step 1: Take input

n = int(input("Enter a positive integer: "))

# Step 2: Initialize sum of divisors

sum_of_divisors = 0

# Step 3: Find divisors from 1 to n/2


for i in range(1, n // 2 + 1):

if n % i == 0:

sum_of_divisors += i # Add divisor to sum

# Step 4: Compare sum with number

if sum_of_divisors == n:

print(n, "is a Perfect Number.")

else:

print(n, "is not a Perfect Number.")

Explanation:

●​ We use range(1, n//2 + 1) to include n/2​

●​ Check if each number divides n without remainder​

●​ Add it to sum​

●​ Finally, compare sum with n​

Example:​
Input: 28​
Divisors: 1, 2, 4, 7, 14​
Sum = 28 → Perfect Number ✅

Summary Table

Ste Operation Description


p
1 Input n Take a positive integer from the
user

2 Initialize sum = 0 Store the sum of divisors

3 Loop i = 1 to n/2 Find divisors

4 If n % i == 0 → sum Add divisor to sum


+= i

5 Compare sum == n If equal → Perfect Number, else not

onus: Easy Python Code (Short Version)


If you already understand the logic, here’s a simple and compact Python version using list
comprehension:

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

# Find all divisors and sum them

if sum([i for i in range(1, n) if n % i == 0]) == n:

print(n, "is a Perfect Number.")

else:

print(n, "is not a Perfect Number.")

How it works:
●​ [i for i in range(1, n) if n % i == 0] creates a list of all divisors.​

●​ sum(...) adds them up.​

●​ Compare directly with n.

5. What is an Anagram?
Two strings are said to be anagrams if they contain the same characters with the same
frequency, but possibly in different order.

For example:

●​ "listen" and "silent" → both contain the same letters → Anagram​

●​ "race" and "care" → same letters → Anagram​

●​ "hello" and "world" → different letters → Not an Anagram​

So, in simple words:

●​ Both strings must have the same length​

●​ Both must have the same characters with equal counts​

Algorithm Used: Sorting and Comparing


We use a simple sorting-based algorithm to check if two strings are anagrams.

Step-by-Step Algorithm:

1.​ Take two strings as input from the user.​

2.​ Convert both strings to lowercase — so that case differences (like A vs a) don’t
matter.​

3.​ Check lengths of both strings. If lengths are different, they cannot be anagrams.​

4.​ Sort both strings alphabetically.​

5.​ Compare the sorted versions:​


○​ If both sorted strings are identical → They are Anagrams.​

○​ Otherwise → Not Anagrams.​

This method works because sorting rearranges characters in the same order, so identical
sets of characters will produce the same sorted result.

C Program to Check if Two Strings are


Anagrams
#include <stdio.h> // Include standard input-output functions

#include <string.h> // Include string handling functions (strlen,


strcmp)

#include <ctype.h> // Include ctype.h for tolower() function

// Function to sort a string using Bubble Sort

void sortString(char str[]) {

int i, j;

char temp;

int len = strlen(str); // Find length of string

// Outer loop: repeat for each character

for (i = 0; i < len - 1; i++) {

// Inner loop: compare adjacent characters

for (j = i + 1; j < len; j++) {

// If current character is greater than next, swap them

if (str[i] > str[j]) {


temp = str[i];

str[i] = str[j];

str[j] = temp;

int main() {

char str1[100], str2[100];

int i;

// Step 1: Ask user to enter first string

printf("Enter first string: ");

scanf("%s", str1);

// Step 2: Ask user to enter second string

printf("Enter second string: ");

scanf("%s", str2);

// Step 3: Convert both strings to lowercase for


case-insensitive comparison

for (i = 0; str1[i]; i++) {

str1[i] = tolower(str1[i]);

}
for (i = 0; str2[i]; i++) {

str2[i] = tolower(str2[i]);

// Step 4: Check if lengths are equal

if (strlen(str1) != strlen(str2)) {

printf("Strings are not Anagrams.\n");

return 0; // Exit program early

// Step 5: Sort both strings

sortString(str1);

sortString(str2);

// Step 6: Compare sorted strings

if (strcmp(str1, str2) == 0) {

printf("Strings are Anagrams.\n");

} else {

printf("Strings are not Anagrams.\n");

return 0; // End of program

}
Explanation of the C Code:

1.​ We use scanf() to take two strings as input.​

2.​ Convert both strings to lowercase using tolower().​

3.​ Compare their lengths using strlen().​

4.​ Sort both strings using the sortString() function.​

5.​ Finally, compare both sorted strings using strcmp().​

6.​ If they are equal → they are anagrams.​

Example:​
Input: listen, silent​
After sorting: eilnst and eilnst → equal → Anagram.

Python Program to Check if Two Strings


are Anagrams
# Step 1: Take input for first string

str1 = input("Enter first string: ")

# Step 2: Take input for second string

str2 = input("Enter second string: ")

# Step 3: Convert both strings to lowercase

# This ensures 'A' and 'a' are treated as same

str1 = [Link]()

str2 = [Link]()
# Step 4: Check if the lengths of both strings are equal

if len(str1) != len(str2):

print("Strings are not Anagrams.")

else:

# Step 5: Sort both strings alphabetically

sorted_str1 = sorted(str1) # returns a sorted list of


characters

sorted_str2 = sorted(str2)

# Step 6: Compare sorted lists

if sorted_str1 == sorted_str2:

print("Strings are Anagrams.")

else:

print("Strings are not Anagrams.")

Explanation of the Python Code (Line by Line):

1.​ input() is used to get both strings.​

2.​ lower() converts them to lowercase to avoid case sensitivity.​

3.​ len() checks if lengths are equal.​

4.​ sorted() rearranges characters in alphabetical order.​

5.​ Compare the two sorted lists:​

○​ If they match → anagram​

○​ Else → not anagram​


Example:​
Input → "Race", "Care"​
After lowercase → "race", "care"​
After sorting → ['a','c','e','r'] and ['a','c','e','r']​
→ They match → Anagram

Bonus: Short and Simple Python Version


a = input("Enter first string: ").lower()

b = input("Enter second string: ").lower()

print("Anagram" if sorted(a) == sorted(b) else "Not Anagram")

This one-line condition:

●​ Takes both inputs​

●​ Converts them to lowercase​

●​ Sorts both​

●​ Compares directly​

●​ Prints result based on comparison​

Summary of the Algorithm

Ste Description
p

1 Take two strings from user


2 Convert both to lowercase

3 Check if lengths are equal

4 Sort both strings alphabetically

5 Compare sorted versions

6 If same → Anagram, else → Not Anagram

[Link] is a Palindrome?
A palindrome is a word, number, or phrase that reads the same forward and backward.

Examples:

●​ madam → same forwards and backwards → Palindrome​

●​ level → Palindrome​

●​ racecar → Palindrome​

●​ hello → Not Palindrome​

So, if a string equals its reverse, it is a Palindrome.

Algorithm (Step-by-Step)
1.​ Take a string as input from the user.​

2.​ Convert it to lowercase (to make comparison case-insensitive).​

3.​ Reverse the string.​


4.​ Compare the original string with its reversed version.​

5.​ If both are the same → Palindrome.​


Otherwise → Not a Palindrome.​

C Program to Check if a String is


Palindrome
#include <stdio.h> // For input and output functions

#include <string.h> // For strlen() and string functions

#include <ctype.h> // For tolower() to convert to lowercase

int main() {

char str[100]; // To store the input string

int i, length;

int isPalindrome = 1; // Flag variable (1 means true, 0 means


false)

// Step 1: Take input from user

printf("Enter a string: ");

scanf("%s", str); // Read string (Note: stops at space)

// Step 2: Convert the string to lowercase

for (i = 0; str[i]; i++) {

str[i] = tolower(str[i]);

}
// Step 3: Find the length of the string

length = strlen(str);

// Step 4: Compare characters from start and end

for (i = 0; i < length / 2; i++) {

// Compare first with last, second with second-last, etc.

if (str[i] != str[length - i - 1]) {

isPalindrome = 0; // If mismatch found, set flag to 0

break; // Exit loop early

// Step 5: Print result based on flag

if (isPalindrome == 1)

printf("The string is a Palindrome.\n");

else

printf("The string is Not a Palindrome.\n");

return 0; // End of program

Explanation of C Code
Ste Description
p

1 scanf() takes string input.

2 tolower() converts all characters to lowercase.

3 strlen() finds the total number of characters.

4 Loop compares str[i] with str[length - i


- 1].

5 If any mismatch → not palindrome.

6 After loop, if no mismatch found → palindrome.

Example 1:​
Input: madam​
Checks: m==m, a==a, d==d → all match → Palindrome

Example 2:​
Input: hello​
Checks: h!=o → Not Palindrome

Python Program to Check if a String is


Palindrome
# Step 1: Take input from the user

string = input("Enter a string: ")


# Step 2: Convert string to lowercase

# This makes the comparison case-insensitive

string = [Link]()

# Step 3: Reverse the string using slicing

reversed_string = string[::-1] # [::-1] reverses the string

# Step 4: Compare original and reversed strings

if string == reversed_string:

print("The string is a Palindrome.")

else:

print("The string is Not a Palindrome.")

Explanation of Python Code (Line by Line)

1.​ input() → gets user input.​

2.​ lower() → ensures case-insensitivity.​

3.​ [::-1] → slicing method to reverse a string.​

4.​ Compare original with reversed string using ==.​

5.​ If equal → Palindrome, else → Not Palindrome.​

Example:

Enter a string: RaceCar


After lowercase → racecar​
Reversed → racecar​
They match → Palindrome

Short Python Version


s = input("Enter a string: ").lower()

print("Palindrome" if s == s[::-1] else "Not Palindrome")

This version:

●​ Takes input​

●​ Converts to lowercase​

●​ Checks equality with reversed version​

●​ Prints result accordingly​

Summary of Algorithm

Ste Action Purpose


p

1 Take input Get the string from user

2 Convert to Ignore case differences


lowercase

3 Reverse the string Compare backward


order
4 Compare both Check if palindrome

5 Print result Display final output

7. What is Frequency of Characters in a String?



The frequency of characters in a string means counting how many times each character
appears in the given string.

Examples:​
String: hello​
Character frequencies:​
h → 1​
e → 1​
l → 2​
o→1

So, each unique character in the string is counted and displayed with the number of
occurrences.

Algorithm (Step-by-Step)

1.​ Take a string as input from the user.​

2.​ Convert the string to lowercase (optional, to make counting case-insensitive).​

3.​ Initialize an array or dictionary to store character counts.​

4.​ Traverse the string character by character.​

5.​ For each character, increase its count by 1.​

6.​ Finally, print each character and its frequency.​


C Program to Calculate Frequency of Characters in a String

#include <stdio.h> // For input and output functions

#include <string.h> // For strlen() function

#include <ctype.h> // For tolower() function

int main() {

char str[100]; // To store the input string

int freq[256] = {0}; // Array to store frequency of all ASCII


characters

int i;

// Step 1: Take input from user

printf("Enter a string: ");

scanf("%[^\n]", str); // Reads string including spaces

// Step 2: Convert to lowercase

for (i = 0; str[i]; i++) {

str[i] = tolower(str[i]);

// Step 3: Calculate frequency of each character

for (i = 0; str[i]; i++) {

if (str[i] != ' ') { // Ignore spaces

freq[(unsigned char)str[i]]++;

}
}

// Step 4: Display frequency of each character

printf("\nCharacter Frequencies:\n");

for (i = 0; i < 256; i++) {

if (freq[i] != 0)

printf("%c → %d\n", i, freq[i]);

return 0; // End of program

Explanation of C Code

Ste Description
p

1 scanf("%[^\n]", str) reads input including spaces.

2 tolower() converts all characters to lowercase.

3 freq[] array stores the count of each character.

4 Loop increments the frequency for each character.


5 A second loop prints all characters that appear at least
once.

Example 1:​
Input: hello​
Output:​
h → 1​
e → 1​
l → 2​
o→1

Example 2:​
Input: Programming​
Output:​
p → 1​
r → 2​
o → 1​
g → 2​
a → 1​
m → 2​
i → 1​
n→1

Python Program to Calculate Frequency of Characters in a String

# Step 1: Take input from the user

string = input("Enter a string: ")

# Step 2: Convert string to lowercase

string = [Link]()

# Step 3: Initialize an empty dictionary

freq = {}
# Step 4: Count frequency of each character

for char in string:

if char != ' ': # Ignore spaces

freq[char] = [Link](char, 0) + 1

# Step 5: Display the frequencies

print("\nCharacter Frequencies:")

for key, value in [Link]():

print(f"{key} → {value}")

Explanation of Python Code (Line by Line)

input() → reads the user input.​


lower() → converts string to lowercase.​
freq = {} → creates an empty dictionary to store frequencies.​
[Link](char, 0) + 1 → increases count of each character.​
Loop prints each character and its frequency.

Example:​
Enter a string: Programming​
After lowercase → programming​
Frequencies:​
p → 1​
r → 2​
o → 1​
g → 2​
a → 1​
m → 2​
i → 1​
n→1

Short Python Version


s = input("Enter a string: ").lower()

freq = {ch: [Link](ch) for ch in set(s) if ch != ' '}

for k, v in [Link]():

print(f"{k} → {v}")

This version:​
Takes input​
Converts to lowercase​
Counts characters using dictionary comprehension​
Prints each character with its frequency

Summary of Algorithm

Ste Action Purpose


p

1 Take input Get string from user

2 Convert to Make case-insensitive


lowercase

3 Count frequency Store counts for each


character

4 Ignore spaces Skip counting spaces

5 Print result Display character frequencies


8. What is String Matching with Wildcards?

String matching with wildcards means checking whether two strings match when one of
them contains special characters that can represent one or more other characters.

Common Wildcards:

●​ ? → matches exactly one character​

●​ * → matches zero or more characters​

Examples:​
Pattern: he*o, String: hello → Match (because * can replace ll)​
Pattern: h?llo, String: hello → Match (because ? replaces e)​
Pattern: he*, String: hero → Match​
Pattern: hi*, String: hello → Not Match

Algorithm (Step-by-Step)

1.​ Take two strings as input: one as text, one as pattern.​

2.​ Traverse both strings character by character.​

3.​ If characters match or pattern has ?, continue checking.​

4.​ If pattern has *, it can match any sequence of characters:​

○​ Try matching * with 0 or more characters in the text.​

5.​ If the entire text matches the pattern, print Match; otherwise, print Not Match.​

C Program to Check if Two Strings Match (with Wildcards)

#include <stdio.h>

// Function to check if two strings match with wildcards

int match(char *pattern, char *text) {


// If both strings reach end, they match

if (*pattern == '\0' && *text == '\0')

return 1;

// If pattern has '*'

if (*pattern == '*') {

// Move to next pattern character and try to match

// '*' can match zero or more characters

return match(pattern + 1, text) || (*text && match(pattern,


text + 1));

// If pattern has '?' or characters match

if (*pattern == '?' || *pattern == *text)

return match(pattern + 1, text + 1);

// If characters do not match

return 0;

int main() {

char pattern[100], text[100];

// Step 1: Take input from user

printf("Enter the text: ");


scanf("%s", text);

printf("Enter the pattern (use * and ? as wildcards): ");

scanf("%s", pattern);

// Step 2: Check match using recursive function

if (match(pattern, text))

printf("The strings Match.\n");

else

printf("The strings Do Not Match.\n");

return 0;

Explanation of C Code

Ste Description
p

1 The function match() recursively checks each character.

2 If both strings end together → match.

3 If pattern contains * → it matches zero or more


characters.
4 If pattern contains ? → it matches exactly one character.

5 Otherwise, both characters must be identical.

6 The main function takes both strings and prints result.

Example 1:​
Input:​
Text: hello​
Pattern: he*o​
Output: Match

Example 2:​
Input:​
Text: hello​
Pattern: h?llo​
Output: Match

Example 3:​
Input:​
Text: hello​
Pattern: hi*​
Output: Not Match

Python Program to Check if Two Strings Match (with Wildcards)

# Step 1: Take input from the user

text = input("Enter the text: ")

pattern = input("Enter the pattern (use * and ? as wildcards): ")

# Step 2: Define recursive function

def match(pattern, text):

# If both reach end, it's a match


if not pattern and not text:

return True

# If pattern starts with '*'

if pattern and pattern[0] == '*':

# '*' can match 0 or more characters

return match(pattern[1:], text) or (text and match(pattern,


text[1:]))

# If pattern starts with '?' or matches first character

if pattern and text and (pattern[0] == '?' or pattern[0] ==


text[0]):

return match(pattern[1:], text[1:])

# Otherwise, not a match

return False

# Step 3: Check and print result

if match(pattern, text):

print("The strings Match.")

else:

print("The strings Do Not Match.")

Explanation of Python Code (Line by Line)

input() → takes input strings.​


match() → recursively compares pattern and text.​
If both are empty → match.​
If * in pattern → try zero or more character matches.​
If ? → matches exactly one character.​
Otherwise, characters must match exactly.

Example:​
Enter the text: hello​
Enter the pattern: he*o​
Output: The strings Match.

Enter the text: hello​


Enter the pattern: hi*​
Output: The strings Do Not Match.

Short Python Version

import re

text = input("Enter the text: ")

pattern = input("Enter the pattern (use * and ? as wildcards): ")

pattern = [Link]('?', '.').replace('*', '.*')

print("Match" if [Link](pattern, text) else "Not Match")

This version:​
Takes input​
Converts wildcards to regular expressions​
Uses [Link]() to check match​
Prints result

Summary of Algorithm

Ste Action Purpose


p

1 Take text and pattern Get strings from user


input
2 Handle * wildcard Matches zero or more
characters

3 Handle ? wildcard Matches exactly one character

4 Compare recursively Check each position

5 Print result Display Match or Not Match

9. What is Bubble Sort?



Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent elements and
swaps them if they are in the wrong order.​
The process continues until the entire list is sorted.

Example:​
Input: [5, 2, 9, 1, 5, 6]​
Steps:

●​ Compare 5 and 2 → swap → [2, 5, 9, 1, 5, 6]​

●​ Compare 9 and 1 → swap → [2, 5, 1, 9, 5, 6]​

●​ Keep repeating until no swaps are needed.​


Output: [1, 2, 5, 5, 6, 9]​

Algorithm (Step-by-Step)

1.​ Take the number of elements and the elements themselves as input.​

2.​ Use two loops:​


○​ Outer loop runs from the first element to the last.​

○​ Inner loop compares adjacent elements and swaps if needed.​

3.​ After each pass, the largest element “bubbles up” to the end.​

4.​ Repeat until the list is sorted.​

5.​ Display the sorted list.​

C Program for Bubble Sort

#include <stdio.h>

int main() {

int arr[100], n, i, j, temp;

// Step 1: Take number of elements as input

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Take array elements as input

printf("Enter %d elements:\n", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Step 3: Perform Bubble Sort

for (i = 0; i < n - 1; i++) {


for (j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap if elements are in wrong order

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

// Step 4: Display sorted array

printf("Sorted array in ascending order:\n");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

Explanation of C Code

Ste Description
p
1 scanf() reads number of elements and their values.

2 Outer loop controls number of passes.

3 Inner loop compares adjacent elements.

4 If the previous element is larger, they are swapped.

5 After each pass, largest element moves to its correct


position.

6 Final loop prints the sorted array.

Example 1:​
Input: 5 2 9 1 5 6​
Output: 1 2 5 5 6 9

Example 2:​
Input: 8 3 7 4 2​
Output: 2 3 4 7 8

Python Program for Bubble Sort

# Step 1: Take input from user

n = int(input("Enter number of elements: "))

arr = []

# Step 2: Read list of elements

print("Enter the elements:")


for i in range(n):

[Link](int(input()))

# Step 3: Perform Bubble Sort

for i in range(n - 1):

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

if arr[j] > arr[j + 1]:

# Swap elements

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

# Step 4: Print sorted array

print("Sorted array in ascending order:")

print(arr)

Explanation of Python Code (Line by Line)

input() → takes number of elements and list values.​


Outer loop → controls number of passes.​
Inner loop → compares and swaps adjacent elements.​
arr[j], arr[j + 1] = arr[j + 1], arr[j] → swaps if needed.​
Finally, prints sorted array.

Example:​
Enter number of elements: 5​
Enter elements: 5 2 9 1 5​
Output: [1, 2, 5, 5, 9]

Short Python Version


arr = list(map(int, input("Enter numbers separated by space:
").split()))

for i in range(len(arr) - 1):

for j in range(len(arr) - i - 1):

if arr[j] > arr[j + 1]:

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

print("Sorted array:", arr)

This version:​
Takes list input in one line​
Sorts using nested loops​
Prints sorted result

Summary of Algorithm

Ste Action Purpose


p

1 Take input Read array elements

2 Compare adjacent Find incorrect order


elements

3 Swap elements Move larger element right

4 Repeat passes Ensure all elements


sorted

5 Print result Display sorted array


10. What is Merge Sort?

Merge Sort is a divide and conquer sorting algorithm. It divides the array into two halves,
recursively sorts them, and then merges the sorted halves to produce the final sorted array.

It is faster than bubble sort for large datasets and works efficiently with a time complexity of
O(n log n).

Example

Input: [38, 27, 43, 3, 9, 82, 10]

Steps:

1.​ Divide → [38, 27, 43, 3] and [9, 82, 10]​

2.​ Divide again until each subarray has one element.​

3.​ Merge subarrays in sorted order.​

Output: [3, 9, 10, 27, 38, 43, 82]

Algorithm (Step-by-Step)

1.​ If the array has only one element, it is already sorted.​

2.​ Divide the array into two halves.​

3.​ Recursively sort both halves.​

4.​ Merge the two sorted halves into a single sorted array.​

5.​ Continue until the entire array is sorted.​

C Program for Merge Sort

#include <stdio.h>
// Function to merge two halves

void merge(int arr[], int left, int mid, int right) {

int i, j, k;

int n1 = mid - left + 1;

int n2 = right - mid;

int L[n1], R[n2];

// Step 1: Copy data to temporary arrays

for (i = 0; i < n1; i++)

L[i] = arr[left + i];

for (j = 0; j < n2; j++)

R[j] = arr[mid + 1 + j];

// Step 2: Merge the temporary arrays

i = 0;

j = 0;

k = left;

while (i < n1 && j < n2) {

if (L[i] <= R[j]) {

arr[k] = L[i];

i++;

} else {
arr[k] = R[j];

j++;

k++;

// Step 3: Copy remaining elements (if any)

while (i < n1) {

arr[k] = L[i];

i++;

k++;

while (j < n2) {

arr[k] = R[j];

j++;

k++;

// Function to divide the array

void mergeSort(int arr[], int left, int right) {

if (left < right) {

int mid = (left + right) / 2;


// Step 1: Divide the array into halves

mergeSort(arr, left, mid);

mergeSort(arr, mid + 1, right);

// Step 2: Merge the sorted halves

merge(arr, left, mid, right);

int main() {

int arr[100], n, i;

// Step 1: Input number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Input elements

printf("Enter %d elements:\n", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Step 3: Perform merge sort

mergeSort(arr, 0, n - 1);
// Step 4: Display sorted array

printf("Sorted array:\n");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

Explanation of C Code

Ste Description
p

1 mergeSort() recursively divides the array into two


halves.

2 merge() merges two sorted halves into one sorted


array.

3 L[] and R[] are temporary arrays used for merging.

4 Comparisons are made to arrange elements in order.


5 Finally, merged result is stored back into the main array.

Example:​
Input: 38 27 43 3 9 82 10​
Output: 3 9 10 27 38 43 82

Python Program for Merge Sort

# Step 1: Define merge sort function

def merge_sort(arr):

if len(arr) > 1:

# Step 2: Find the middle point

mid = len(arr) // 2

# Step 3: Divide array into two halves

left_half = arr[:mid]

right_half = arr[mid:]

# Step 4: Recursively sort both halves

merge_sort(left_half)

merge_sort(right_half)

# Step 5: Merge sorted halves

i = j = k = 0
# Compare elements and merge

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:

arr[k] = right_half[j]

j += 1

k += 1

# Copy remaining elements

while i < len(left_half):

arr[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

# Step 6: Input and call function

arr = list(map(int, input("Enter numbers separated by space:


").split()))

merge_sort(arr)
print("Sorted array:", arr)

Explanation of Python Code (Line by Line)

merge_sort() → recursive function that sorts the list.​


mid = len(arr)//2 → splits the list into two halves.​
merge_sort(left_half) and merge_sort(right_half) → recursively sort both
parts.​
Merging step → compares and arranges elements in order.​
Finally, sorted list is printed.

Example:​
Input: 38 27 43 3 9 82 10​
Output: Sorted array: [3, 9, 10, 27, 38, 43, 82]

Short Python Version

def merge_sort(arr):

if len(arr) <= 1:

return arr

mid = len(arr) // 2

left = merge_sort(arr[:mid])

right = merge_sort(arr[mid:])

return sorted(left + right)

arr = list(map(int, input("Enter numbers separated by space:


").split()))

print("Sorted array:", merge_sort(arr))


This version:​
Recursively divides the list​
Uses Python’s built-in sorted() for merging​
Returns the final sorted list

Summary of Algorithm

Ste Action Purpose


p

1 Divide the array Split into halves

2 Recursively sort Sort left and right halves

3 Merge Combine sorted halves

4 Repeat Until the entire array is sorted

5 Output result Display sorted list

11. What is a Leap Year?



A leap year is a year that has 366 days instead of 365.​
An extra day (February 29) is added to keep the calendar year synchronized with the
astronomical year.

Rules for Leap Year:

1.​ If a year is divisible by 4, it may be a leap year.​

2.​ But if it is divisible by 100, it is not a leap year.​

3.​ However, if it is divisible by 400, it is a leap year.​


Examples:

●​ 2020 → Divisible by 4 → Leap Year​

●​ 1900 → Divisible by 100 but not by 400 → Not a Leap Year​

●​ 2000 → Divisible by 400 → Leap Year​

●​ 2023 → Not divisible by 4 → Not a Leap Year​

Algorithm (Step-by-Step)

1.​ Take a year as input from the user.​

2.​ Check if the year is divisible by 400 → Leap Year.​

3.​ Else if divisible by 100 → Not a Leap Year.​

4.​ Else if divisible by 4 → Leap Year.​

5.​ Otherwise → Not a Leap Year.​

6.​ Print the result.​

C Program to Check Leap Year

#include <stdio.h>

int main() {

int year;

// Step 1: Take year as input

printf("Enter a year: ");

scanf("%d", &year);
// Step 2: Apply leap year conditions

if (year % 400 == 0) {

printf("%d is a Leap Year.\n", year);

else if (year % 100 == 0) {

printf("%d is Not a Leap Year.\n", year);

else if (year % 4 == 0) {

printf("%d is a Leap Year.\n", year);

else {

printf("%d is Not a Leap Year.\n", year);

return 0;

Explanation of C Code

Ste Description
p

1 scanf() takes input year from user.


2 If divisible by 400 → leap year.

3 Else if divisible by 100 → not leap year.

4 Else if divisible by 4 → leap year.

5 Otherwise → not leap year.

Example 1:​
Input: 2020​
Output: 2020 is a Leap Year.

Example 2:​
Input: 1900​
Output: 1900 is Not a Leap Year.

Example 3:​
Input: 2000​
Output: 2000 is a Leap Year.

Python Program to Check Leap Year

# Step 1: Take input from the user

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

# Step 2: Apply leap year conditions

if year % 400 == 0:

print(f"{year} is a Leap Year.")

elif year % 100 == 0:

print(f"{year} is Not a Leap Year.")


elif year % 4 == 0:

print(f"{year} is a Leap Year.")

else:

print(f"{year} is Not a Leap Year.")

Explanation of Python Code (Line by Line)

input() → reads the year as a string.​


int() → converts it to an integer.​
if-elif-else → checks divisibility conditions.​
% → modulus operator checks divisibility.​
Prints whether the year is leap or not.

Example:​
Enter a year: 2024​
Output: 2024 is a Leap Year.

Short Python Version

y = int(input("Enter a year: "))

print("Leap Year" if (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0))


else "Not a Leap Year")

This version:​
Takes input​
Uses a single-line conditional expression​
Prints result accordingly

Summary of Algorithm
Ste Action Purpose
p

1 Take input Get year from user

2 Check divisibility by 400 Confirm leap year

3 Check divisibility by 100 Exclude non-leap


years

4 Check divisibility by 4 Confirm leap year

5 Print result Display if leap or not

12. What are Non-Repeating Characters?



Non-repeating characters are the characters that appear only once in a given string.​
These characters do not repeat anywhere else in the string.

Examples:​
String: programming​
Non-repeating characters: p, o, a, i, n

String: hello​
Non-repeating characters: h, e, o

Algorithm (Step-by-Step)

1.​ Take a string as input from the user.​

2.​ Convert the string to lowercase (to make it case-insensitive).​


3.​ Count the frequency of each character.​

4.​ Identify characters whose frequency is 1.​

5.​ Display all such non-repeating characters.​

C Program to Find Non-Repeating Characters in a String

#include <stdio.h>

#include <string.h>

#include <ctype.h>

int main() {

char str[100];

int freq[256] = {0};

int i;

// Step 1: Take input from user

printf("Enter a string: ");

scanf("%[^\n]", str); // Reads string including spaces

// Step 2: Convert to lowercase

for (i = 0; str[i]; i++) {

str[i] = tolower(str[i]);

// Step 3: Count frequency of each character


for (i = 0; str[i]; i++) {

if (str[i] != ' ') {

freq[(unsigned char)str[i]]++;

// Step 4: Display non-repeating characters

printf("Non-repeating characters: ");

for (i = 0; str[i]; i++) {

if (str[i] != ' ' && freq[(unsigned char)str[i]] == 1) {

printf("%c ", str[i]);

printf("\n");

return 0;

Explanation of C Code

Ste Description
p

1 scanf("%[^\n]", str) reads full string including spaces.


2 tolower() converts characters to lowercase for uniform
comparison.

3 freq[] array stores frequency of each character using ASCII


index.

4 A loop checks if frequency equals 1 (non-repeating).

5 Prints all such unique characters.

Example 1:​
Input: Programming​
Output: p o a i n

Example 2:​
Input: Hello​
Output: h e o

Python Program to Find Non-Repeating Characters

# Step 1: Take input from user

string = input("Enter a string: ")

# Step 2: Convert to lowercase

string = [Link]()

# Step 3: Initialize a dictionary to store frequency

freq = {}
# Step 4: Count frequency of each character

for ch in string:

if ch != ' ': # Ignore spaces

freq[ch] = [Link](ch, 0) + 1

# Step 5: Display non-repeating characters

print("Non-repeating characters:", end=" ")

for ch in string:

if ch != ' ' and freq[ch] == 1:

print(ch, end=" ")

print()

Explanation of Python Code (Line by Line)

input() → takes the string from user.​


lower() → converts all letters to lowercase.​
[Link](ch, 0) + 1 → increases count for each character.​
Loop checks frequency; if equal to 1 → prints character.

Example:​
Enter a string: Programming​
Output: Non-repeating characters: p o a i n

Short Python Version

s = input("Enter a string: ").lower()


print("Non-repeating characters:", ' '.join([c for c in s if c != '
' and [Link](c) == 1]))

This version:​
Takes input​
Converts to lowercase​
Uses list comprehension with count() to find unique characters​
Prints them in a single line

Summary of Algorithm

Ste Action Purpose


p

1 Take input Get string from user

2 Convert to lowercase Make comparison


case-insensitive

3 Count character Track occurrences


frequency

4 Identify non-repeating Check frequency = 1

5 Print result Display all unique characters


13. What is Substring Replacement?

Substring replacement means finding a specific part (substring) inside a string and replacing
it with another substring.

Examples:​
Original string: I like cats​
Replace "cats" with "dogs" → I like dogs

Original string: hello world​


Replace "world" with "Python" → hello Python

Algorithm (Step-by-Step)

1.​ Take the original string, substring to be replaced, and new substring as input.​

2.​ Search for the position of the old substring in the main string.​

3.​ If found, replace it with the new substring.​

4.​ Print the updated string.​

C Program to Replace a Substring in a String

#include <stdio.h>

#include <string.h>

int main() {

char str[200], sub[50], newSub[50], result[200];

int i, j, k;

int found = 0;

// Step 1: Take input from user


printf("Enter the main string: ");

fgets(str, sizeof(str), stdin);

str[strcspn(str, "\n")] = '\0'; // Remove newline character

printf("Enter the substring to replace: ");

scanf("%s", sub);

printf("Enter the new substring: ");

scanf("%s", newSub);

// Step 2: Search for substring and replace

for (i = 0; str[i] != '\0'; i++) {

found = 1;

for (j = 0; sub[j] != '\0'; j++) {

if (str[i + j] != sub[j]) {

found = 0;

break;

if (found) {

// Step 3: Perform replacement

for (k = 0; k < i; k++) {

result[k] = str[k];
}

result[k] = '\0';

strcat(result, newSub);

strcat(result, str + i + strlen(sub));

break;

// Step 4: Print result

if (found)

printf("Updated string: %s\n", result);

else

printf("Substring not found.\n");

return 0;

Explanation of C Code

Ste Description
p

1 fgets() reads input string including spaces.


2 Loops through str to find the first occurrence of sub.

3 If found, builds new string by concatenating parts using


strcat().

4 If not found, displays message.

5 Prints final string after replacement.

Example 1:​
Input:​
Main String → I love cats​
Substring → cats​
New Substring → dogs​
Output: I love dogs

Example 2:​
Input:​
Main String → hello world​
Substring → world​
New Substring → Python​
Output: hello Python

Python Program to Replace a Substring in a String

# Step 1: Take inputs

string = input("Enter the main string: ")

old_sub = input("Enter the substring to replace: ")

new_sub = input("Enter the new substring: ")

# Step 2: Replace substring


new_string = [Link](old_sub, new_sub)

# Step 3: Print result

print("Updated string:", new_string)

Explanation of Python Code (Line by Line)

input() → gets user input.​


replace(old_sub, new_sub) → replaces all occurrences of old substring with new
substring.​
print() → displays updated string.

Example:​
Enter the main string: I love cats​
Enter the substring to replace: cats​
Enter the new substring: dogs​
Output: Updated string: I love dogs

Short Python Version

s = input("Enter string: ")

print([Link](input("Old substring: "), input("New substring: ")))

This version:​
Takes all inputs in one go​
Replaces substring directly using replace()​
Prints updated result

Summary of Algorithm
Ste Action Purpose
p

1 Take inputs Get original, old, and new


substrings

2 Search substring Find the part to replace

3 Replace Perform substitution


substring

4 Print result Display final string

14. What is Heap Sort?



Heap Sort is a comparison-based sorting algorithm that uses a binary heap data
structure.​
It first builds a max heap (largest element at the root), then repeatedly removes the largest
element from the heap and rebuilds it until the array is sorted.

Examples:​
Unsorted array: 12, 11, 13, 5, 6, 7​
Sorted array: 5, 6, 7, 11, 12, 13

Algorithm (Step-by-Step)

1.​ Build a max heap from the input array.​

2.​ Swap the root element (largest) with the last element.​

3.​ Reduce the heap size by one.​


4.​ Heapify the root element again to restore the heap property.​

5.​ Repeat steps 2–4 until the array is sorted.​

C Program to Implement Heap Sort

#include <stdio.h>

// Function to heapify a subtree rooted at index i

void heapify(int arr[], int n, int i) {

int largest = i; // Initialize largest as root

int left = 2 * i + 1; // left child

int right = 2 * i + 2; // right child

// If left child is larger than root

if (left < n && arr[left] > arr[largest])

largest = left;

// If right child is larger than largest so far

if (right < n && arr[right] > arr[largest])

largest = right;

// If largest is not root

if (largest != i) {

int temp = arr[i];

arr[i] = arr[largest];
arr[largest] = temp;

// Recursively heapify the affected subtree

heapify(arr, n, largest);

// Main function to perform heap sort

void heapSort(int arr[], int n) {

int i;

// Step 1: Build max heap

for (i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);

// Step 2: Extract elements one by one from heap

for (i = n - 1; i > 0; i--) {

// Move current root to end

int temp = arr[0];

arr[0] = arr[i];

arr[i] = temp;

// Call heapify on the reduced heap

heapify(arr, i, 0);

}
}

// Function to print array

void printArray(int arr[], int n) {

for (int i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[100], n;

// Step 1: Take input

printf("Enter number of elements: ");

scanf("%d", &n);

printf("Enter %d elements: ", n);

for (int i = 0; i < n; i++)

scanf("%d", &arr[i]);

// Step 2: Perform heap sort

heapSort(arr, n);

// Step 3: Print sorted array


printf("Sorted array: ");

printArray(arr, n);

return 0;

Explanation of C Code

Ste Description
p

1 heapify() ensures the heap property (parent > children).

2 heapSort() first builds a max heap, then swaps root with last
element.

3 Each swap reduces heap size and restores heap property.

4 Final result is a sorted array in ascending order.

Example:​
Input: 12 11 13 5 6 7​
Heap building → [13, 11, 12, 5, 6, 7]​
After sorting → [5, 6, 7, 11, 12, 13]

Python Program to Implement Heap Sort

# Function to heapify a subtree rooted at index i


def heapify(arr, n, i):

largest = i

left = 2 * i + 1

right = 2 * i + 2

# Check if left child exists and is greater

if left < n and arr[left] > arr[largest]:

largest = left

# Check if right child exists and is greater

if right < n and arr[right] > arr[largest]:

largest = right

# If largest is not root

if largest != i:

arr[i], arr[largest] = arr[largest], arr[i]

heapify(arr, n, largest)

# Main heap sort function

def heap_sort(arr):

n = len(arr)

# Step 1: Build max heap

for i in range(n // 2 - 1, -1, -1):


heapify(arr, n, i)

# Step 2: Extract elements from heap

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

arr[i], arr[0] = arr[0], arr[i] # swap

heapify(arr, i, 0)

# Driver code

arr = [12, 11, 13, 5, 6, 7]

heap_sort(arr)

print("Sorted array:", arr)

Explanation of Python Code (Line by Line)

heapify() → ensures heap property (max at root).​


heap_sort() → builds max heap and extracts largest element iteratively.​
arr[i], arr[0] = arr[0], arr[i] → swaps first and last elements.​
Final output is a sorted array in ascending order.

Example:​
Input: [12, 11, 13, 5, 6, 7]​
Output: Sorted array: [5, 6, 7, 11, 12, 13]

Short Python Version

def heap_sort(arr):

import heapq

[Link](arr)
return [[Link](arr) for _ in range(len(arr))]

arr = [12, 11, 13, 5, 6, 7]

print("Sorted array:", heap_sort(arr))

This version uses Python’s built-in heapq library for simplicity.

Summary of Algorithm

Ste Action Purpose


p

1 Build max heap Arrange elements in heap form

2 Swap root with last element Place largest at correct


position

3 Heapify reduced heap Maintain heap property

4 Repeat until done Get fully sorted array

5 Print result Display sorted output

15. What is Rank Replacement in an Array?



Rank replacement means replacing each element of an array with its rank when the array is
sorted in ascending order.​
The smallest element gets rank 1, the next smallest gets rank 2, and so on.
Examples:​
Array: [40, 10, 30, 20]​
Sorted order: [10, 20, 30, 40]​
Ranks: [4, 1, 3, 2] → after replacing each element with its rank.

Algorithm (Step-by-Step)

1.​ Take array input from the user.​

2.​ Create a copy of the array and sort it in ascending order.​

3.​ For each element in the original array, find its position (rank) in the sorted array.​

4.​ Replace the element with its rank.​

5.​ Print the updated array.​

C Program to Replace Each Element by Its Rank

#include <stdio.h>

int main() {

int arr[100], sorted[100], rank[100];

int n, i, j, temp;

// Step 1: Take input

printf("Enter number of elements: ");

scanf("%d", &n);

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++) {


scanf("%d", &arr[i]);

sorted[i] = arr[i]; // Copy array

// Step 2: Sort the copied array (ascending order)

for (i = 0; i < n - 1; i++) {

for (j = i + 1; j < n; j++) {

if (sorted[i] > sorted[j]) {

temp = sorted[i];

sorted[i] = sorted[j];

sorted[j] = temp;

// Step 3: Assign ranks

for (i = 0; i < n; i++) {

for (j = 0; j < n; j++) {

if (arr[i] == sorted[j]) {

rank[i] = j + 1; // Rank is index + 1

break;

}
// Step 4: Print ranked array

printf("Array after replacing elements by their rank:\n");

for (i = 0; i < n; i++) {

printf("%d ", rank[i]);

printf("\n");

return 0;

Explanation of C Code

Ste Description
p

1 Input number of elements and store them in arr.

2 Copy array to sorted for sorting.

3 Sort sorted array using nested loops (Bubble Sort).

4 For each element in original array, find position in sorted array.

5 Position (index + 1) represents rank.


6 Print ranks as the new array.

Example 1:​
Input: 40 10 30 20​
Sorted: 10 20 30 40​
Output: 4 1 3 2

Example 2:​
Input: 5 10 15​
Sorted: 5 10 15​
Output: 1 2 3

Python Program to Replace Each Element by Its Rank

# Step 1: Take input

arr = list(map(int, input("Enter elements separated by space:


").split()))

# Step 2: Create a sorted copy

sorted_arr = sorted(arr)

# Step 3: Replace each element with its rank

ranked_arr = [sorted_arr.index(x) + 1 for x in arr]

# Step 4: Print result

print("Array after replacing elements by their rank:")

print(ranked_arr)
Explanation of Python Code (Line by Line)

input() → reads elements as a string.​


map(int, input().split()) → converts to a list of integers.​
sorted(arr) → returns sorted version.​
index(x) + 1 → gives the rank (since indexing starts from 0).​
Prints final list with each element replaced by its rank.

Example:​
Enter elements separated by space: 40 10 30 20​
Output: Array after replacing elements by their rank:​
[4, 1, 3, 2]

Short Python Version

arr = list(map(int, input().split()))

print([sorted(arr).index(x) + 1 for x in arr])

This version directly replaces each element by its rank in one line.

Summary of Algorithm

Ste Action Purpose


p

1 Take input Get array elements

2 Sort copy Determine ranking order


3 Find rank Compare element with sorted
array

4 Replace Assign rank number


element

5 Print result Display ranked array

16. What is Circular Rotation of an Array?



Circular rotation means shifting the elements of an array left or right by a certain
number of positions (K).​
The elements that move beyond the array boundary come back around to the other side.

Imagine you have an array:​


[1, 2, 3, 4, 5]

If you rotate it to the right by 1 position, every element moves one step to the right, and
the last element wraps around to the beginning.

After 1 right rotation → [5, 1, 2, 3, 4]

If you rotate it again (K = 2) → [4, 5, 1, 2, 3]

This is called a circular or cyclic rotation, because the elements “wrap around” in a circle
— nothing is lost, only moved.

How to Do Left Rotation (Just for Understanding)


To rotate left, the logic is similar but in reverse:

●​ Copy the first K elements to temp.​

●​ Shift remaining elements left.​

●​ Place the temp elements at the end.


Example (Right Rotation):​
Array: [1, 2, 3, 4, 5], K = 2​
After 2 right rotations → [4, 5, 1, 2, 3]

Example (Left Rotation):​


Array: [1, 2, 3, 4, 5], K = 2​
After 2 left rotations → [3, 4, 5, 1, 2]

Algorithm (Step-by-Step for Right Rotation)

1.​ Take array and rotation value K as input.​

2.​ Normalize K using K = K % n (if K > n).​

3.​ Copy the last K elements to a temporary array.​

4.​ Shift the remaining elements to the right by K positions.​

5.​ Copy the temporary elements to the beginning.​

6.​ Print the rotated array.​

C Program to Perform Circular (Right) Rotation by K Positions

#include <stdio.h>

int main() {

int arr[100], temp[100];

int n, k, i, j;

// Step 1: Take input


printf("Enter number of elements: ");

scanf("%d", &n);

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++)

scanf("%d", &arr[i]);

printf("Enter value of K (number of rotations): ");

scanf("%d", &k);

// Step 2: Normalize K

k = k % n;

// Step 3: Store last K elements in temp

for (i = 0; i < k; i++)

temp[i] = arr[n - k + i];

// Step 4: Shift remaining elements to right

for (i = n - 1; i >= k; i--)

arr[i] = arr[i - k];

// Step 5: Copy temp elements to beginning

for (i = 0; i < k; i++)

arr[i] = temp[i];
// Step 6: Print rotated array

printf("Array after %d right rotations:\n", k);

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");

return 0;

Explanation of C Code

Ste Description
p

1 Input the array and value of K.

2 K = K % n ensures rotation count is within array


length.

3 Temporary array stores last K elements.

4 Elements are shifted right by K positions.

5 Temporary elements are copied to the start of array.


6 Final rotated array is printed.

Example 1:​
Input:​
Array = 1 2 3 4 5​
K = 2​
Output: 4 5 1 2 3

Example 2:​
Array = 10 20 30 40 50 60​
K = 3​
Output: 40 50 60 10 20 30

Python Program to Perform Circular (Right) Rotation by K Positions

# Step 1: Take inputs

arr = list(map(int, input("Enter elements separated by space:


").split()))

k = int(input("Enter number of rotations: "))

# Step 2: Normalize K

k = k % len(arr)

# Step 3: Perform rotation

rotated = arr[-k:] + arr[:-k]

# Step 4: Print result

print("Array after", k, "right rotations:")

print(rotated)
Explanation of Python Code (Line by Line)

input() → takes elements as space-separated numbers.​


k % len(arr) → ensures valid rotation count.​
arr[-k:] + arr[:-k] → slicing method for right rotation.​
Prints the final rotated list.

Example:​
Enter elements separated by space: 1 2 3 4 5​
Enter number of rotations: 2​
Output: Array after 2 right rotations:​
[4, 5, 1, 2, 3]

Short Python Version

arr = list(map(int, input().split()))

k = int(input())

print(arr[-k % len(arr):] + arr[:-k % len(arr)])

This version performs right rotation in one line using slicing and modular arithmetic.

Summary of Algorithm

Ste Action Purpose


p

1 Take input Read array and K

2 Normalize K Handle K > n


3 Copy last K Preserve end section
elements

4 Shift elements Move items to new positions

5 Insert copied part Complete rotation

6 Print result Display rotated array

17. Write a Code to Find Non-Repeating


Elements in an Array

Definition
A non-repeating element in an array is an element that appears exactly once — i.e., it
does not have any duplicates.

For example,​
if the array is:​
[1, 2, 3, 2, 1, 4]​
→ The elements 3 and 4 each appear only once.​
Hence, 3 and 4 are non-repeating elements.

Logic Behind the Problem


The key idea is to count the frequency of each element.

●​ If an element’s frequency = 1 → it is non-repeating.​

●​ Otherwise → it is repeating.​
We can find the frequency by comparing each element with all others.

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the size of the array n.​

3.​ Input the array elements one by one.​

4.​ For each element in the array (arr[i]):​

○​ Initialize a counter count = 0.​

○​ Loop through the entire array (arr[j]):​

■​ If arr[i] == arr[j], increment count.​

○​ After checking all elements:​

■​ If count == 1, it means this element occurs only once → print it.​

5.​ End the program.​

Dry Run Example


Let’s take:​
arr = [1, 2, 3, 2, 1, 4]

i arr[i] Compared With Count Result

0 1 [1,2,3,2,1,4] 2 Skip

1 2 [1,2,3,2,1,4] 2 Skip
2 3 [1,2,3,2,1,4] 1 Print 3

3 2 [1,2,3,2,1,4] 2 Skip

4 1 [1,2,3,2,1,4] 2 Skip

5 4 [1,2,3,2,1,4] 1 Print 4

Output: 3 4

C Program to Find Non-Repeating Elements in an Array


#include <stdio.h>

int main() {

int arr[100];

int n, i, j, count;

// Step 1: Input array size

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Input array elements

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);
}

// Step 3: Find and print non-repeating elements

printf("Non-repeating elements are: ");

for (i = 0; i < n; i++) {

count = 0; // reset counter for each element

// Step 4: Count frequency of arr[i]

for (j = 0; j < n; j++) {

if (arr[i] == arr[j]) {

count++;

// Step 5: If element appears only once, print it

if (count == 1) {

printf("%d ", arr[i]);

printf("\n");

return 0;

}
Line-by-Line Explanation

Line / Section Description

int arr[100]; Declares an integer array with a capacity of 100 elements.

scanf("%d", &n); Reads the number of elements n.

Loop for (i = 0; i < Reads each array element one by one.


n; i++)

Inner loop for (j = 0; Compares each element with every other element to count
j < n; j++) how many times it appears.

if (count == 1) If frequency = 1, then it’s non-repeating → print it.

Example Execution
Input:

Enter number of elements: 6

Enter 6 elements: 1 2 3 2 1 4

Processing:

●​ 1 → appears twice​

●​ 2 → appears twice​
●​ 3 → appears once​

●​ 4 → appears once​

Output:

Non-repeating elements are: 3 4

Python Program (Simple Version)


# Step 1: Take input from user

arr = list(map(int, input("Enter elements separated by space:


").split()))

# Step 2: Find and print non-repeating elements

print("Non-repeating elements are:", end=" ")

for i in arr:

if [Link](i) == 1:

print(i, end=" ")

print()

Short Python Version (One Line)


arr = list(map(int, input("Enter elements: ").split()))

print(*[x for x in arr if [Link](x) == 1])


Complexity Analysis

Operation Time Complexity Explanation

Outer loop O(n) Runs once per element

Inner loop O(n) Compares with all elements

Total O(n²) Double nested loop

Space O(1) Uses only constant extra


memory

Optimized Approach (Conceptual)


If we want to improve time complexity to O(n),​
we can use a hash map / dictionary to count frequencies in one pass,​
then print all elements with frequency 1.​
(This approach is common in higher-level languages like Python, C++, or Java.)

Summary of Algorithm

Ste Action Purpose


p

1 Take input array Get user data

2 Count frequency Identify how often each element


appears
3 Check frequency = 1 Find unique elements

4 Print results Display non-repeating numbers

5 End program Finish execution

Final Output Example:

Input: 1 2 3 2 1 4

Output: 3 4

18. Write a Code to Check for the


Longest Palindrome in an Array

Definition
A palindrome is a number or string that reads the same forward and backward.​
Examples:

●​ Numbers → 121, 1331, 11 → Palindromes​

●​ Words → madam, level, racecar → Palindromes​

In this problem, you are given an array of integers, and the goal is to find the longest
palindrome number present in that array.

Example:

Input Array: [121, 131, 20, 1331, 14541, 34]


Here,

●​ 121 → Palindrome​

●​ 131 → Palindrome​

●​ 1331 → Palindrome​

●​ 14541 → Palindrome​
Among them, the longest palindrome is 14541 (has the maximum number of
digits).​

Output: Longest Palindrome = 14541

Logic Behind the Problem


1.​ We must check each element of the array to see if it is a palindrome.​

2.​ A number is palindrome if it is equal to its reverse.​

3.​ While checking each element:​

○​ If it’s a palindrome, compare its length (number of digits) with the longest
palindrome found so far.​

○​ Keep updating the maximum length and longest palindrome.​

4.​ After checking all elements, print the palindrome with the maximum length.​

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the number of elements (n) and the array elements.​

3.​ Initialize two variables:​

○​ longest = -1 → to store the longest palindrome number.​


○​ maxLength = 0 → to store the number of digits in the longest palindrome.​

4.​ For each element arr[i] in the array:​

○​ Copy it to a temporary variable num.​

○​ Reverse the digits using a loop:​

■​ Extract digits using % 10 and reconstruct the reverse.​

○​ If the reversed number equals the original → it’s a palindrome.​

○​ If palindrome, count its digits and compare with maxLength.​

■​ If greater, update longest and maxLength.​

5.​ After the loop, print longest if found; otherwise, print that no palindrome exists.​

6.​ End​

Dry Run Example


Input: [121, 131, 20, 1331, 14541, 34]

Ste Number Revers Palindrome? Length Longest So Far


p e

1 121 121 Yes 3 121

2 131 131 Yes 3 121 (equal


length)

3 20 02 No — 121

4 1331 1331 Yes 4 1331


5 14541 14541 Yes 5 14541

6 34 43 No — 14541

Output:

Longest Palindrome = 14541

C Program to Find the Longest Palindrome in an Array


#include <stdio.h>

int main() {

int arr[100];

int n, i;

int num, rev, digit;

int longest = -1; // To store the longest palindrome

int maxLength = 0; // To store number of digits in longest


palindrome

// Step 1: Input array size

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Input array elements

printf("Enter %d elements: ", n);


for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Step 3: Process each element

for (i = 0; i < n; i++) {

num = arr[i];

rev = 0;

int temp = num;

// Step 4: Reverse the number

while (temp > 0) {

digit = temp % 10;

rev = rev * 10 + digit;

temp /= 10;

// Step 5: Check palindrome

if (rev == num) {

// Count number of digits

int length = 0, temp2 = num;

while (temp2 > 0) {

temp2 /= 10;

length++;
}

// Step 6: Update longest palindrome

if (length > maxLength) {

maxLength = length;

longest = num;

// Step 7: Display result

if (longest != -1)

printf("Longest Palindrome: %d\n", longest);

else

printf("No Palindrome found.\n");

return 0;

Explanation of C Code

Step Description
Input section User enters number of elements and array values.

Reverse logic % 10 extracts last digit, then build reversed number as rev = rev *
10 + digit.

Palindrome If num == rev, the number is a palindrome.


check

Digit count Loop divides by 10 until number becomes 0 → counts digits.

Comparison If current palindrome’s digit count > stored maxLength, update both.

Output Prints the palindrome with maximum digits.

Example Execution
Input:

Enter number of elements: 6

Enter 6 elements: 121 131 20 1331 14541 34

Output:

Longest Palindrome: 14541

Python Program to Find Longest Palindrome in an


Array
# Step 1: Input list

arr = list(map(int, input("Enter elements separated by space:


").split()))

# Step 2: Initialize tracking variables

longest = -1

max_len = 0

# Step 3: Check each element

for num in arr:

s = str(num)

if s == s[::-1]: # Check if palindrome

if len(s) > max_len:

max_len = len(s)

longest = num

# Step 4: Output result

if longest != -1:

print("Longest Palindrome:", longest)

else:

print("No Palindrome found.")

Explanation of Python Code


1.​ str(num) → converts number to string.​

2.​ s[::-1] → reverses the string.​

3.​ If both match → palindrome.​

4.​ Track the longest palindrome by comparing string length.​

5.​ Print the final result.​

Complexity Analysis

Operation Time Space Explanation


Complexity Complexity

Reversing O(d) O(1) where d = number of digits


number

Loop through O(n × d) O(1) for n numbers


array

Overall O(n × d) O(1) Efficient for small to medium


arrays

Summary of Algorithm

Ste Action Purpose


p

1 Take array input Get data from user


2 Reverse each number Check palindrome

3 Compare with original Identify palindromes

4 Measure length Find longest one

5 Update result Keep max-length palindrome

6 Output Display result or “No Palindrome found”

Sample Outputs
Example 1

Input: 121 131 20 1331 14541 34

Output: Longest Palindrome: 14541

Example 2

Input: 12 23 45 67

Output: No Palindrome found.

Example 3

Input: 11 22 333 4444 55555

Output: Longest Palindrome: 55555


Key Takeaways
●​ A palindrome remains the same when reversed.​

●​ Use % 10 and / 10 to reverse a number in C.​

●​ Keep track of the maximum digit length while checking palindromes.​

●​ Both C and Python can handle this efficiently with O(n) complexity.

19. Write a Code to Find the Factorial of


a Number

Definition
The factorial of a number is the product of all positive integers less than or equal to
that number.​
It is represented using the symbol n!

Mathematically:

n!=n×(n−1)×(n−2)×…×2×1n! = n × (n - 1) × (n - 2) × … × 2 × 1n!=n×(n−1)×(n−2)×…×2×1

Examples:

●​ 5!=5×4×3×2×1=1205! = 5 × 4 × 3 × 2 × 1 = 1205!=5×4×3×2×1=120​

●​ 4!=4×3×2×1=244! = 4 × 3 × 2 × 1 = 244!=4×3×2×1=24​

●​ 1!=11! = 11!=1​

●​ 0!=10! = 10!=1 (by definition)​

Logic Behind the Problem


To find the factorial:
1.​ Start with 1 as the initial result.​

2.​ Multiply it by every number from 1 to n.​

3.​ Keep updating the result after each multiplication.​

4.​ The final result after the loop ends is n!​

Alternatively, it can be done using recursion, where:

factorial(n)=n×factorial(n−1)factorial(n) = n × factorial(n - 1)factorial(n)=n×factorial(n−1)

and the recursion ends when n == 0 or n == 1.

Algorithm (Step-by-Step)
Iterative Approach (Using Loop)

1.​ Start​

2.​ Input a number n.​

3.​ Initialize fact = 1.​

4.​ If n == 0, factorial = 1.​

5.​ For each number i from 1 to n, do:​

○​ fact = fact * i​

6.​ Output the value of fact.​

7.​ End​

Recursive Approach (Using Function Call)

1.​ Define a function factorial(n).​

2.​ If n == 0 or n == 1, return 1.​


3.​ Else, return n × factorial(n - 1).​

4.​ In main, call this function with the input number and print the result.​

Dry Run Example


Input: n = 5

Ste i fact (after multiplication)


p

1 1 1×1=1

2 2 1×2=2

3 3 2×3=6

4 4 6 × 4 = 24

5 5 24 × 5 = 120

Output: Factorial = 120

C Program (Iterative Method)


#include <stdio.h>

int main() {

int n, i;
unsigned long long fact = 1; // To store large results

// Step 1: Take input

printf("Enter a number: ");

scanf("%d", &n);

// Step 2: Check for negative number

if (n < 0) {

printf("Factorial of a negative number doesn't exist.\n");

} else {

// Step 3: Loop to multiply numbers

for (i = 1; i <= n; i++) {

fact = fact * i;

// Step 4: Display result

printf("Factorial of %d = %llu\n", n, fact);

return 0;

Explanation of C Code
Step Description

unsigned long long Declared as unsigned long long to store very large
fact = 1; results.

if (n < 0) Factorial is not defined for negative numbers.

for (i = 1; i <= n; Loop multiplies fact by every number from 1 to n.


i++)

printf() Displays the result.

C Program (Recursive Method)


#include <stdio.h>

long long factorial(int n) {

if (n == 0 || n == 1)

return 1; // Base case

else

return n * factorial(n - 1); // Recursive call

int main() {

int n;
printf("Enter a number: ");

scanf("%d", &n);

if (n < 0)

printf("Factorial of a negative number doesn't exist.\n");

else

printf("Factorial of %d = %lld\n", n, factorial(n));

return 0;

Explanation of Recursive Logic

Step Function Call Return Value

factorial(5) 5 × factorial(4)

factorial(4) 4 × factorial(3)

factorial(3) 3 × factorial(2)

factorial(2) 2 × factorial(1)

factorial(1) 1
Final Result 5 × 4 × 3 × 2 × 1 = 120

Example Execution
Input:

Enter a number: 5

Output:

Factorial of 5 = 120

Python Program (Iterative Method)


# Step 1: Take input

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

# Step 2: Initialize factorial

fact = 1

# Step 3: Check for negative

if n < 0:

print("Factorial of a negative number doesn't exist.")

else:

for i in range(1, n + 1):

fact *= i
print("Factorial of", n, "=", fact)

Python Program (Recursive Method)


def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)

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

if n < 0:

print("Factorial of a negative number doesn't exist.")

else:

print("Factorial of", n, "=", factorial(n))

Dry Run (Recursive Example for n = 4)

Function Call Returned Value

factorial(4) 4 × factorial(3)
factorial(3) 3 × factorial(2)

factorial(2) 2 × factorial(1)

factorial(1) 1

Result 4 × 3 × 2 × 1 = 24

Output: Factorial = 24

Complexity Analysis

Method Time Complexity Space Explanation


Complexity

Iterative O(n) O(1) Simple loop with constant memory

Recursiv O(n) O(n) Recursive call stack uses memory


e

Summary of Algorithm

Ste Action Purpose


p

1 Take input n Read number from user


2 Initialize fact = 1 Prepare for multiplication

3 Multiply numbers 1 to n Compute factorial

4 Handle base cases n = 0 or n = 1 gives 1

5 Print result Display factorial

Sample Outputs
Example 1

Input: 5

Output: Factorial of 5 = 120

Example 2

Input: 0

Output: Factorial of 0 = 1

Example 3

Input: -3

Output: Factorial of a negative number doesn't exist.

Key Takeaways
●​ Factorial is the product of all positive integers up to n.​

●​ 0! is always 1.​

●​ Use iteration for efficiency, and recursion for elegant logic.​

●​ Factorial grows very fast, so use large data types (long long, unsigned long
long).​

20. Write a Code to Check Whether a


Number is an Armstrong Number

Definition
An Armstrong number (also called a Narcissistic number) is a number that is equal to
the sum of its own digits each raised to the power of the number of digits.

In other words, for a number with n digits:

Armstrong Number=d1n+d2n+d3n+⋯+dnn=original number\text{Armstrong Number} = d_1^n


+ d_2^n + d_3^n + \dots + d_n^n = \text{original number}Armstrong
Number=d1n​+d2n​+d3n​+⋯+dnn​=original number

Examples

1.​ 153​
13+53+33=1+125+27=153→Armstrong number1^3 + 5^3 + 3^3 = 1 + 125 + 27 =
153 → \text{Armstrong number}13+53+33=1+125+27=153→Armstrong number
2.​ 9474​
94+44+74+44=6561+256+2401+16=9234→Not Armstrong9^4 + 4^4 + 7^4 + 4^4 =
6561 + 256 + 2401 + 16 = 9234 → \text{Not
Armstrong}94+44+74+44=6561+256+2401+16=9234→Not Armstrong
3.​ 9474​
94+44+74+44=9474→Armstrong number9^4 + 4^4 + 7^4 + 4^4 = 9474 →
\text{Armstrong number}94+44+74+44=9474→Armstrong number
4.​ 370​
33+73+03=27+343+0=370→Armstrong number3^3 + 7^3 + 0^3 = 27 + 343 + 0 =
370 → \text{Armstrong number}33+73+03=27+343+0=370→Armstrong number

Logic Behind the Problem


To determine if a number is Armstrong:

1.​ Find the number of digits (n) in the number.​

2.​ Extract each digit of the number.​

3.​ Raise each digit to the power n and calculate the sum.​

4.​ Compare the sum with the original number.​

5.​ If both are equal → it is an Armstrong number; else → not Armstrong.​

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input a number num.​

3.​ Store the number in a temporary variable temp.​

4.​ Initialize sum = 0.​

5.​ Count the number of digits in num (say n).​

6.​ Repeat until temp == 0:​

○​ Extract the last digit: digit = temp % 10​

○​ Add digit^n to sum​

○​ Remove the last digit: temp = temp / 10​

7.​ If sum == num, print "Armstrong number", else "Not Armstrong".​


8.​ End​

Dry Run Example


Input: 153

Ste temp digit digit³ su


p m

1 153 3 27 27

2 15 5 125 152

3 1 1 1 153

sum = 153 = original number → Armstrong number

C Program
#include <stdio.h>

#include <math.h> // For pow() function

int main() {

int num, temp, digit, count = 0;

double sum = 0;

// Step 1: Take input

printf("Enter a number: ");


scanf("%d", &num);

temp = num;

// Step 2: Count number of digits

while (temp != 0) {

temp = temp / 10;

count++;

temp = num;

// Step 3: Calculate sum of each digit raised to power of count

while (temp != 0) {

digit = temp % 10;

sum += pow(digit, count);

temp = temp / 10;

// Step 4: Compare and print result

if ((int)sum == num)

printf("%d is an Armstrong number.\n", num);

else

printf("%d is not an Armstrong number.\n", num);


return 0;

Explanation of C Code

Step Description

math.h Used for the pow() function to raise digits to


powers.

count Stores number of digits.

sum += pow(digit, Adds each digit raised to power of number of digits.


count)

if ((int)sum == Checks equality with original number.


num)

printf() Prints whether Armstrong or not.

Dry Run of the C Program


Input: 9474

Ste digit coun pow(digit, sum


p t count)
1 4 4 256 256

2 7 4 2401 2657

3 4 4 256 2913

4 9 4 6561 9474

✅ Output: 9474 is an Armstrong number.

Python Program
# Step 1: Take input

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

# Step 2: Convert to string to count digits

n = len(str(num))

# Step 3: Calculate sum of digits raised to power n

sum = 0

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** n

temp //= 10
# Step 4: Compare and display

if num == sum:

print(num, "is an Armstrong number.")

else:

print(num, "is not an Armstrong number.")

Explanation of Python Code

Step Description

len(str(num)) Finds number of digits easily.

digit = temp Extracts last digit.


% 10

digit ** n Raises digit to power of total digits.

sum += digit Adds powered digits.


** n

temp //= 10 Removes last digit.

if num == Checks Armstrong condition.


sum:
Dry Run Example (Python)
Input: 371​
Digits: 3

33+73+13=27+343+1=3713^3 + 7^3 + 1^3 = 27 + 343 + 1 = 37133+73+13=27+343+1=371

✅ Output: 371 is an Armstrong number.

Short Python Version


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

print(f"{n} is an Armstrong number." if n == sum(int(d)**len(str(n))


for d in str(n)) else f"{n} is not an Armstrong number.")

Complexity Analysis

Operation Time Complexity Space Description


Complexity

Counting digits O(log₁₀n) O(1) Counting number of digits

Main loop O(log₁₀n) O(1) Each digit processed


once

Overall O(log₁₀n) O(1) Efficient

Example Outputs
Example 1
Input: 153

Output: 153 is an Armstrong number.

Example 2

Input: 370

Output: 370 is an Armstrong number.

Example 3

Input: 123

Output: 123 is not an Armstrong number.

Summary of Algorithm

Ste Action Purpose


p

1 Take input Read number from user

2 Count digits Needed for exponent

3 Extract each digit Use modulo and division

4 Raise to power and Compute powered sum


sum

5 Compare and print Check Armstrong condition


Key Takeaways
●​ An Armstrong number equals the sum of its digits each raised to the power of the
total digits.​

●​ Works for any number of digits (not just 3).​

●​ Use pow() in C or **** in Python for power calculation.​

●​ Time complexity grows linearly with number of digits, not the number’s size.​

21. Write a Program to Find the Sum of


Natural Numbers Using Recursion

Definition
The sum of natural numbers refers to the total of all positive integers from 1 to n.

Mathematically,

Sum=1+2+3+⋯+n\text{Sum} = 1 + 2 + 3 + \dots + nSum=1+2+3+⋯+n

This can also be expressed using the formula:

Sum=n(n+1)2\text{Sum} = \frac{n(n + 1)}{2}Sum=2n(n+1)​

But in this program, we will compute the sum using recursion, not by formula.

Logic Behind the Problem


The recursive relationship for the sum of natural numbers is:

sum(n)=n+sum(n - 1)\text{sum(n)} = n + \text{sum(n - 1)}sum(n)=n+sum(n - 1)

Here:

●​ The problem is divided into smaller sub-problems.​

●​ Each recursive call reduces n by 1.​

●​ The base case is when n == 1, at which point the recursion stops.​

Example

If n = 5:

sum(5)=5+sum(4)sum(5) = 5 + sum(4)sum(5)=5+sum(4) sum(4)=4+sum(3)sum(4) = 4 +


sum(3)sum(4)=4+sum(3) sum(3)=3+sum(2)sum(3) = 3 + sum(2)sum(3)=3+sum(2)
sum(2)=2+sum(1)sum(2) = 2 + sum(1)sum(2)=2+sum(1) sum(1)=1sum(1) = 1sum(1)=1

Adding them up:

sum(5)=5+4+3+2+1=15sum(5) = 5 + 4 + 3 + 2 + 1 = 15sum(5)=5+4+3+2+1=15

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the number n.​

3.​ Define a recursive function sum(n) that:​

○​ Returns 1 if n == 1 (base case)​

○​ Otherwise returns n + sum(n - 1)​

4.​ In main, call sum(n) and print the result.​

5.​ End​
Dry Run Example
Input: n = 4

Function Call Return Value

sum(4) 4 + sum(3)

sum(3) 3 + sum(2)

sum(2) 2 + sum(1)

sum(1) 1 (base case)

Backtracking:

sum(4)=4+3+2+1=10sum(4) = 4 + 3 + 2 + 1 = 10sum(4)=4+3+2+1=10

Output: Sum = 10

C Program
#include <stdio.h>

// Recursive function to find sum of natural numbers

int sumOfNaturalNumbers(int n) {

if (n == 1)

return 1; // Base case

else

return n + sumOfNaturalNumbers(n - 1); // Recursive call


}

int main() {

int n;

// Step 1: Take input

printf("Enter a positive integer: ");

scanf("%d", &n);

// Step 2: Check for valid input

if (n <= 0)

printf("Please enter a positive integer.\n");

else

printf("Sum of first %d natural numbers = %d\n", n,


sumOfNaturalNumbers(n));

return 0;

Explanation of C Code

Step Description
sumOfNaturalNumbers() Recursive function that adds n to sum of previous
numbers.

if (n == 1) Base condition to stop recursion.

return n + Recursive step.


sumOfNaturalNumbers(n - 1);

scanf() Reads the input value for n.

printf() Displays the result.

Dry Run of C Code


Input: n = 3

Call Stack Function Returned Value

1 sum(3) 3 + sum(2)

2 sum(2) 2 + sum(1)

3 sum(1) 1

Final 3+2+1=6 Output: 6

Output:

Sum of first 3 natural numbers = 6


Python Program
# Recursive function to find sum of natural numbers

def sum_natural(n):

if n == 1:

return 1 # Base case

else:

return n + sum_natural(n - 1) # Recursive call

# Step 1: Take input

n = int(input("Enter a positive integer: "))

# Step 2: Check for valid input

if n <= 0:

print("Please enter a positive integer.")

else:

print("Sum of first", n, "natural numbers =", sum_natural(n))

Explanation of Python Code

Step Description
def sum_natural(n): Defines a recursive function.

if n == 1: Base case that ends recursion.

return n + Recursive call to compute


sum_natural(n - 1) sum.

int(input()) Takes user input.

print() Displays the sum.

Dry Run Example (Python)


Input: n = 5

Recursive Returned Value


Call

sum_natural(5) 5 + sum_natural(4)

sum_natural(4) 4 + sum_natural(3)

sum_natural(3) 3 + sum_natural(2)

sum_natural(2) 2 + sum_natural(1)

sum_natural(1) 1
Result 5 + 4 + 3 + 2 + 1 = 15

Output:

Sum of first 5 natural numbers = 15

Short Python Version


def sum_natural(n):

return 1 if n == 1 else n + sum_natural(n - 1)

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

print("Sum =", sum_natural(n))

Complexity Analysis

Operation Time Space Explanation


Complexity Complexity

Recursive O(n) O(n) Each call adds one number and stores
sum in call stack

Example Outputs
Example 1

Input: 5
Output: Sum of first 5 natural numbers = 15

Example 2

Input: 10

Output: Sum of first 10 natural numbers = 55

Example 3

Input: -4

Output: Please enter a positive integer.

Summary of Algorithm

Ste Action Purpose


p

1 Take input Get n from user

2 Check base Stop recursion at 1


case

3 Recursive call Sum numbers from n to 1

4 Return sum Backtrack and compute


total

5 Print result Display output


Key Takeaways
●​ Recursion divides the problem into smaller subproblems until a base condition is
met.​

●​ For sum of natural numbers:​


sum(n)=n+sum(n−1)sum(n) = n + sum(n - 1)sum(n)=n+sum(n−1)
●​ Time complexity is O(n), and recursion depth equals n.​

●​ Works best for small or medium n values due to stack limits.

Write a Program to Add Two Matrices using


Multi-dimensional Array

Definition

Matrix addition is the process of adding two matrices of the same order (same number of
rows and columns) by adding their corresponding elements.

If we have:

A=[aij],B=[bij]A = [a_{ij}], \quad B = [b_{ij}]A=[aij​],B=[bij​]

then their sum C=A+B=[cij]C = A + B = [c_{ij}]C=A+B=[cij​], where:

cij=aij+bijc_{ij} = a_{ij} + b_{ij}cij​=aij​+bij​

Examples

Example 1

Matrix A

[123456]\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix}[14​25​36​]

Matrix B

[789123]\begin{bmatrix} 7 & 8 & 9 \\ 1 & 2 & 3 \end{bmatrix}[71​82​93​]

Result (A + B)
[81012579]\begin{bmatrix} 8 & 10 & 12 \\ 5 & 7 & 9 \end{bmatrix}[85​107​129​]

Logic Behind the Problem

To add two matrices:

1.​ The matrices must have the same number of rows and columns.​

2.​ Add each element in Matrix A with the corresponding element in Matrix B.​

3.​ Store the result in a third matrix (say, Matrix C).​

C[i][j]=A[i][j]+B[i][j]C[i][j] = A[i][j] + B[i][j]C[i][j]=A[i][j]+B[i][j]

Algorithm (Step-by-Step)

1.​ Start​

2.​ Input number of rows and columns (say r and c).​

3.​ Declare three 2D arrays: A[r][c], B[r][c], C[r][c].​

4.​ Input elements for matrix A.​

5.​ Input elements for matrix B.​

6.​ For each element:​

○​ Add corresponding elements: C[i][j] = A[i][j] + B[i][j]​

7.​ Display the resulting matrix C.​

8.​ End​

Dry Run Example

Input

Rows = 2, Columns = 3

A = [[1, 2, 3], [4, 5, 6]]


B = [[7, 8, 9], [1, 2, 3]]

Step-by-Step Calculation

i j A[i][j] B[i][j] C[i][j] = A[i][j] + B[i][j]

0 0 1 7 8

0 1 2 8 10

0 2 3 9 12

1 0 4 1 5

1 1 5 2 7

1 2 6 3 9

✅ Output Matrix:
[81012579]\begin{bmatrix} 8 & 10 & 12 \\ 5 & 7 & 9 \end{bmatrix}[85​107​129​]

C Program

#include <stdio.h>

int main() {

int A[10][10], B[10][10], C[10][10];

int i, j, rows, cols;


// Step 1: Input number of rows and columns

printf("Enter number of rows and columns: ");

scanf("%d %d", &rows, &cols);

// Step 2: Input elements of first matrix

printf("\nEnter elements of Matrix A:\n");

for(i = 0; i < rows; i++) {

for(j = 0; j < cols; j++) {

scanf("%d", &A[i][j]);

// Step 3: Input elements of second matrix

printf("\nEnter elements of Matrix B:\n");

for(i = 0; i < rows; i++) {

for(j = 0; j < cols; j++) {

scanf("%d", &B[i][j]);

// Step 4: Add corresponding elements

for(i = 0; i < rows; i++) {

for(j = 0; j < cols; j++) {

C[i][j] = A[i][j] + B[i][j];


}

// Step 5: Display Result

printf("\nResultant Matrix (A + B):\n");

for(i = 0; i < rows; i++) {

for(j = 0; j < cols; j++) {

printf("%d ", C[i][j]);

printf("\n");

return 0;

Explanation of C Code

Step Description

A[10][10], B[10][10], Declares three 2D arrays.


C[10][10]

scanf("%d %d", &rows, Reads number of rows and columns.


&cols)
Nested loops Used for traversing through each element of the
(for(i)...for(j)) matrix.

C[i][j] = A[i][j] + Adds corresponding elements of A and B.


B[i][j];

Output loop Prints final matrix in tabular form.

Dry Run of C Program

Input:

2 2

A = 1 2

3 4

B = 5 6

7 8

Process:

Ste i j A[i][j] B[i][j] C[i][j]


p

1 0 0 1 5 6

2 0 1 2 6 8

3 1 0 3 7 10
4 1 1 4 8 12

✅ Output:
6 8

10 12

Python Program

# Step 1: Input rows and columns

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

cols = int(input("Enter number of columns: "))

# Step 2: Input first matrix

print("Enter elements of Matrix A:")

A = [[int(input()) for j in range(cols)] for i in range(rows)]

# Step 3: Input second matrix

print("Enter elements of Matrix B:")

B = [[int(input()) for j in range(cols)] for i in range(rows)]

# Step 4: Add corresponding elements

C = [[A[i][j] + B[i][j] for j in range(cols)] for i in range(rows)]

# Step 5: Display result


print("\nResultant Matrix (A + B):")

for row in C:

print(row)

Explanation of Python Code

Step Description

A = [[int(input()) for j in Takes matrix input using list


range(cols)] for i in range(rows)] comprehension.

C = [[A[i][j] + B[i][j] for j in Adds corresponding elements.


range(cols)] for i in range(rows)]

for row in C: Prints each row neatly.

Dry Run (Python)

Input:

rows = 2

cols = 2

A = [[1, 2], [3, 4]]

B = [[5, 6], [7, 8]]

Output:

[6, 8]
[10, 12]

✅ Result: Matrix addition successful.

Complexity Analysis

Operation Time Space Description


Complexity Complexity

Input & Output O(r × c) O(1) Reading and printing each


element

Addition O(r × c) O(r × c) Each element processed once

Overall O(r × c) O(r × c) Efficient matrix addition

Example Outputs

Example 1

Input:

A = [[1, 2, 3],

[4, 5, 6]]

B = [[7, 8, 9],

[1, 2, 3]]

Output:

[8, 10, 12]

[5, 7, 9]
Example 2

Input:

A = [[10, 20],

[30, 40]]

B = [[1, 2],

[3, 4]]

Output:

[11, 22]

[33, 44]

Summary of Algorithm

Ste Action Purpose


p

1 Take input for rows and columns Define matrix size

2 Input two matrices Data for addition

3 Add corresponding elements Perform matrix addition

4 Display resulting matrix Show output


Key Takeaways

●​ Both matrices must have the same dimensions.​

●​ Addition is performed element-wise.​

●​ Works for any dimension (2×2, 3×3, etc.).​

●​ Efficient and simple — uses nested loops.​

25. Write a Program for Binary to


Decimal Conversion

Definition
The binary number system uses only two digits: 0 and 1.​
Each digit in a binary number represents a power of 2, starting from the rightmost digit
(which represents 202^020).

The decimal equivalent of a binary number is calculated by multiplying each bit by 2its
position2^{\text{its position}}2its position and summing all the results.

Example

Convert (1011)₂ to decimal:

(1011)2=(1×23)+(0×22)+(1×21)+(1×20)(1011)_2 = (1 × 2^3) + (0 × 2^2) + (1 × 2^1) + (1 ×


2^0)(1011)2​=(1×23)+(0×22)+(1×21)+(1×20) =8+0+2+1=11= 8 + 0 + 2 + 1 = 11=8+0+2+1=11

✅ Output: (1011)₂ = (11)₁₀

Logic Behind the Problem


To convert binary to decimal:
1.​ Start from the rightmost digit.​

2.​ For each binary digit (bit), multiply it by 2 raised to its positional index.​

3.​ Add all those products to get the decimal equivalent.​

Alternatively, you can process the binary number digit by digit using:

decimal=decimal×2+current bit\text{decimal} = \text{decimal} × 2 + \text{current


bit}decimal=decimal×2+current bit

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the binary number (as integer or string).​

3.​ Initialize decimal = 0 and base = 1.​

4.​ Extract digits one by one from right to left.​

5.​ For each digit:​

○​ Multiply the digit (0 or 1) by the current base.​

○​ Add it to decimal.​

○​ Multiply base by 2 for the next digit.​

6.​ Print the value of decimal.​

7.​ End​

Dry Run Example


Input: Binary number = 1101

Ste Digit Base (Power of Calculation Decimal


p 2)
1 1 1 (2⁰) 1×1 = 1 1

2 0 2 (2¹) 0×2 = 0 1

3 1 4 (2²) 1×4 = 4 5

4 1 8 (2³) 1×8 = 8 13

✅ Output: 1101₂ = 13₁₀

C Program
#include <stdio.h>

int main() {

long long binary;

int decimal = 0, base = 1, rem;

// Step 1: Take input

printf("Enter a binary number: ");

scanf("%lld", &binary);

// Step 2: Convert binary to decimal

while (binary > 0) {

rem = binary % 10; // Extract last digit

decimal += rem * base; // Multiply by current base


binary = binary / 10; // Remove last digit

base = base * 2; // Increase base (2⁰, 2¹, 2²...)

// Step 3: Display result

printf("Decimal equivalent = %d\n", decimal);

return 0;

Explanation of C Code

Step Description

scanf("%lld", Reads binary number as long long to handle large


&binary); inputs.

rem = binary % 10; Extracts last digit of binary number.

decimal += rem * Adds weighted contribution to decimal result.


base;

base = base * 2; Updates base for next bit position.

while (binary > 0) Processes all digits until binary becomes 0.


printf() Displays final decimal value.

Dry Run of C Code


Input: 1011

Iteration binary rem bas decima


e l

1 1011 1 1 1

2 101 1 2 3

3 10 0 4 3

4 1 1 8 11

✅ Output: Decimal equivalent = 11

Python Program
# Step 1: Take input as string

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

# Step 2: Initialize decimal value

decimal = 0

power = 0
# Step 3: Process digits from right to left

for digit in binary[::-1]:

decimal += int(digit) * (2 ** power)

power += 1

# Step 4: Display result

print("Decimal equivalent =", decimal)

Explanation of Python Code

Step Description

binary[::-1 Reverses the string to process from right to


] left.

int(digit) Converts character digit to integer.

2 ** power Raises 2 to the positional power.

decimal += Adds weighted binary digit value.


...

print() Displays the final decimal result.


Simplified Python Version (Using Built-in Function)
binary = input("Enter a binary number: ")

print("Decimal equivalent =", int(binary, 2))

Explanation:​
int(binary, 2) directly converts a binary string into its decimal equivalent.

Dry Run Example (Python)


Input: binary = "1010"

Ste digit power Calculation decima


p l

1 0 0 0×2⁰ = 0 0

2 1 1 1×2¹ = 2 2

3 0 2 0×2² = 0 2

4 1 3 1×2³ = 8 10

✅ Output: Decimal equivalent = 10

Complexity Analysis

Operation Time Space Explanation


Complexity Complexity
Binary O(n) O(1) Each digit is processed once
traversal

Overall O(n) O(1) Linear in number of binary


digits

Example Outputs
Example 1

Input: 1010

Output: Decimal equivalent = 10

Example 2

Input: 1111

Output: Decimal equivalent = 15

Example 3

Input: 100000

Output: Decimal equivalent = 32

Summary of Algorithm

Ste Action Purpose


p
1 Take binary input Get binary digits from user

2 Initialize base = 1 Start with 2⁰

3 Extract each bit Using modulo and division

4 Add weighted value Multiply bit × base

5 Update base Multiply by 2 each time

6 Print decimal Display result

Key Takeaways
●​ Binary numbers use base 2, decimal uses base 10.​

●​ Conversion involves summing powers of 2 multiplied by respective bits.​

●​ You can use:​

○​ Manual method (loop, logic)​

○​ Built-in conversion (int(binary, 2) in Python)​

●​ Efficient and easy to extend to other bases (octal, hexadecimal).

26. Write a Program to Check Whether a Character is a


Vowel or Consonant

Definition
In the English alphabet:​
Vowels are: A, E, I, O, U (both uppercase and lowercase).​
All other alphabet letters are consonants.

The program should check whether a given character input by the user is a vowel or a
consonant.

Examples

Input Output

A Vowel

e Vowel

t Consonant

B Consonant

1 Not an alphabet
character

Logic Behind the Problem

To determine if a character is a vowel or consonant:

1.​ Check if the character is an alphabet letter (either a-z or A-Z).​


If not, print “Not an alphabet.”​

2.​ If it is an alphabet, check if it matches any of these characters:​


a, e, i, o, u, A, E, I, O, U​

3.​ If yes → Vowel, else → Consonant​


Algorithm (Step-by-Step)

1.​ Start​

2.​ Input a character ch.​

3.​ Check if ch is an alphabet using conditions:​


(ch >= 'a' && ch <= 'z') or (ch >= 'A' && ch <= 'Z')​

4.​ If not an alphabet → print “Not an alphabet.”​

5.​ Else, check:​

○​ If ch is a, e, i, o, u, A, E, I, O, U, then print “Vowel”​

○​ Else print “Consonant”​

6.​ End​

Dry Run Example

Input Condition Output

a alphabet → vowel Vowel

D alphabet → Consonant
consonant

3 not alphabet Not an


alphabet

C Program

#include <stdio.h>
int main() {

char ch;

// Step 1: Take input

printf("Enter a character: ");

scanf("%c", &ch);

// Step 2: Check if alphabet

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {

// Step 3: Check for vowel

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch


== 'u' ||

ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch


== 'U') {

printf("%c is a vowel.\n", ch);

} else {

printf("%c is a consonant.\n", ch);

else {

printf("%c is not an alphabet character.\n", ch);

}
return 0;

Explanation of C Code

Step Description

char ch; Declares a variable to store the


character.

scanf("%c", &ch); Reads a single character.

`(ch >= 'a' && ch <= 'z')

`if (ch == 'a'

else Otherwise, it’s a consonant.

Dry Run of C Program

Input: O

Step-by-Step Execution:

Step Condition Result

ch = 'O' Alphabet check ✅ True


Is 'O' a vowel? ✅ Yes

Output 'O' is a
vowel.

✅ Output:
O is a vowel.

Python Program

# Step 1: Take input

ch = input("Enter a character: ")

# Step 2: Check if single character and alphabet

if len(ch) == 1 and [Link]():

# Step 3: Check vowel or consonant

if [Link]() in ('a', 'e', 'i', 'o', 'u'):

print(ch, "is a vowel.")

else:

print(ch, "is a consonant.")

else:

print(ch, "is not an alphabet character.")


Explanation of Python Code

Step Description

input() Reads user input.

[Link]() Returns True if input is alphabetic.

[Link]() Converts to lowercase for easier


comparison.

in ('a', 'e', 'i', Checks if vowel.


'o', 'u')

else If not vowel → consonant.

Dry Run (Python)

Input: t

Step Description Output

Input character = t Alphabet → Yes

Lowercase t in vowels? → No → Consonant

✅ Output t is a
consonant.
Complexity Analysis

Operation Time Complexity Space Description


Complexity

Checking character type O(1) O(1) Single comparison

Checking vowel condition O(1) O(1) Constant lookup

Overall O(1) O(1) Fast and efficient

Example Outputs

Example 1

Input: e

Output: e is a vowel.

Example 2

Input: G

Output: G is a consonant.

Example 3

Input: 5

Output: 5 is not an alphabet character.

Summary of Algorithm
Ste Action Purpose
p

1 Take a character as User input


input

2 Check if it’s alphabetic Validate input

3 Check vowel list Identify vowels

4 Else → consonant Classify remaining letters

5 Display result Output

Key Takeaways

●​ Only A, E, I, O, U (and lowercase equivalents) are vowels.​

●​ Every other alphabetic letter is a consonant.​

●​ Always check that input is an alphabet before comparison.​

●​ Works for both uppercase and lowercase letters.

27. Write a Program to Find an


Automorphic Number

Definition
An Automorphic Number is a number whose square ends with the same digits as the
number itself.

In simple terms:​
If the last digits of (number²) are the same as the number, it is Automorphic.

Examples

Number Square Ends with Same Result


Digits?

5 25 Yes (ends with 5) Automorphic

6 36 Yes (ends with 6) Automorphic

25 625 Yes (ends with 25) Automorphic

76 5776 Yes (ends with 76) Automorphic

7 49 No Not Automorphic

✅ So, 5, 6, 25, and 76 are Automorphic numbers.

Logic Behind the Problem


1.​ Find the square of the given number.​

2.​ Compare the last digits of the square with the original number.​

3.​ If they are the same, it’s an Automorphic number.​

To extract and compare the last digits, we can use the modulus operator (%).
For example:​
If number = 25 → square = 625​
We need to compare last 2 digits of 625 with 25.​
We can use:

625 % 100 == 25

✅ True → Automorphic

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input a number num from the user.​

3.​ Find its square → square = num * num.​

4.​ Initialize a variable temp = num for calculation.​

5.​ Count the number of digits in num.​

6.​ Find the remainder of the square using % with 10^digits.​

○​ last_digits = square % (10^digits)​

7.​ If last_digits == num, it is Automorphic.​


Else, Not Automorphic.​

8.​ Print the result.​

9.​ End​

Dry Run Example


Input: num = 76
Ste Action Value
p

1 Square = 76 × 76 5776

2 Digits in num = 2 2

3 10² = 100 100

4 5776 % 100 = 76 76

5 Compare: 76 == True
76

✅ Output: 76 is an Automorphic number.

C Program
#include <stdio.h>

#include <math.h>

int main() {

int num, square, temp, digits = 0, lastDigits;

// Step 1: Take input from the user

printf("Enter a number: ");

scanf("%d", &num);
// Step 2: Calculate square

square = num * num;

// Step 3: Count digits in num

temp = num;

while (temp > 0) {

digits++;

temp /= 10;

// Step 4: Extract last digits from square

int divisor = pow(10, digits);

lastDigits = square % divisor;

// Step 5: Compare and print result

if (lastDigits == num)

printf("%d is an Automorphic number.\n", num);

else

printf("%d is not an Automorphic number.\n", num);

return 0;

}
Explanation of C Code

Step Description

scanf("%d", Takes number input from user.


&num);

square = num * Finds square of the number.


num;

while (temp > 0) Counts the digits of the number.

pow(10, digits) Calculates 10 raised to the number of


digits.

square % divisor Extracts last digits of the square.

if (lastDigits == Checks Automorphic condition.


num)

printf() Prints final result.

Dry Run of C Code


Input: 25

Variable Value
num 25

square 625

digits 2

divisor 100

lastDigits 625 % 100 = 25

Compare 25 == 25 → True

✅ Output: 25 is an Automorphic number.

Python Program
# Step 1: Take input from user

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

# Step 2: Find square

square = num ** 2

# Step 3: Convert both to strings

num_str = str(num)

square_str = str(square)
# Step 4: Check if square ends with number

if square_str.endswith(num_str):

print(f"{num} is an Automorphic number.")

else:

print(f"{num} is not an Automorphic number.")

Explanation of Python Code

Step Description

num = Reads integer input.


int(input())

square = num Calculates square of the number.


** 2

str() Converts integers to strings for


comparison.

.endswith() Checks if one string ends with another.

print() Displays final output.

Alternate Python (Mathematical Approach)


num = int(input("Enter a number: "))
square = num * num

# Step 1: Find number of digits

digits = len(str(num))

# Step 2: Extract last digits from square

if square % (10 ** digits) == num:

print(f"{num} is an Automorphic number.")

else:

print(f"{num} is not an Automorphic number.")

Dry Run Example (Python)


Input: num = 6​
square = 6 ** 2 = 36​
len(str(num)) = 1​
36 % 10 = 6 → True

✅ Output: 6 is an Automorphic number.

Example Outputs
Example 1

Input: 5

Output: 5 is an Automorphic number.

Example 2
Input: 76

Output: 76 is an Automorphic number.

Example 3

Input: 7

Output: 7 is not an Automorphic number.

Complexity Analysis

Operation Time Complexity Space Explanation


Complexity

Counting digits O(log₁₀ n) O(1) Iterates over digits

Modulus operation O(1) O(1) Constant time

Overall O(log n) O(1) Efficient and fast

Summary of Algorithm

Ste Action Purpose


p

1 Input number Read user input


2 Find square Get squared value

3 Count digits To extract last digits

4 Compare using Check Automorphic condition


modulus

5 Print result Display output

Key Takeaways
●​ Automorphic Number → number whose square ends with the number itself.​

●​ Can be checked using:​

○​ String comparison (endswith() in Python)​

○​ Mathematical approach (using % and powers of 10)​

●​ Common examples: 5, 6, 25, 76, 376, 625​

28. Write a Code to Find the ASCII Value


of a Character

Definition
ASCII (American Standard Code for Information Interchange) is a numeric
representation of characters in computers.

Each character (letter, digit, symbol) has a corresponding integer ASCII code.
For example:

Character ASCII Value

A 65

B 66

a 97

b 98

0 48

space 32

@ 64

So, finding the ASCII value simply means converting a character into its integer code
equivalent.

Logic Behind the Problem


●​ Every character has an integer value in memory.​

●​ In C, characters are internally stored as integers according to the ASCII table.​

●​ We can get the ASCII value by using %d in printf() when printing a character.​

●​ In Python, the built-in ord() function returns the ASCII value of a character.​
Algorithm (Step-by-Step)
1.​ Start​

2.​ Input a character from the user.​

3.​ Convert the character to its ASCII value.​

4.​ Print the ASCII value.​

5.​ End​

Dry Run Example


Input: A

Ste Action Result


p

1 Input character → 'A' -

2 Convert to ASCII → 65 -

3 Print ASCII value Output: 65

Output:

ASCII value of A is 65

C Program to Find ASCII Value of a Character


#include <stdio.h>
int main() {

char ch;

// Step 1: Take input from the user

printf("Enter a character: ");

scanf("%c", &ch);

// Step 2: Print ASCII value

printf("The ASCII value of '%c' is %d\n", ch, ch);

return 0;

Explanation of C Code

Line / Section Description

char ch; Declares a variable to store a character.

scanf("%c", Reads a single character from the user.


&ch);

printf("%d", Prints the ASCII value of that character using %d.


ch);
%c Used to print the character itself.

%d Used to print the integer (ASCII) value of the character.

Dry Run of C Code


Input: z

Variable Value

ch 'z'

ASCII value 122

Output:

The ASCII value of 'z' is 122

Python Program to Find ASCII Value of a Character


# Step 1: Take input from the user

ch = input("Enter a character: ")

# Step 2: Get ASCII value using ord()

ascii_value = ord(ch)
# Step 3: Display the result

print(f"The ASCII value of '{ch}' is {ascii_value}")

Explanation of Python Code

Step Description

input Reads user input as a string.


()

ord(c Returns the ASCII value of the first character in


h) ch.

print Displays both the character and its ASCII code.


()

Dry Run (Python)


Input: G​
ord('G') = 71

Output:

The ASCII value of 'G' is 71

Example Outputs
Example 1
Input: A

Output: The ASCII value of 'A' is 65

Example 2

Input: 9

Output: The ASCII value of '9' is 57

Example 3

Input: $

Output: The ASCII value of '$' is 36

Reverse of ASCII (Bonus Info)


If you know an ASCII value and want to find its character:

Languag Function Example Output


e

C (char)val (char) A
ue 65

Python chr(value chr(65 'A'


) )

Complexity Analysis
Operation Time Complexity Space Explanation
Complexity

Input O(1) O(1) Constant time input

ASCII conversion O(1) O(1) Single step conversion

Overall O(1) O(1) Efficient and constant time

Summary of Algorithm

Ste Action Purpose


p

1 Take input Get character from user

2 Convert to ASCII Map character to numeric


code

3 Print output Display ASCII value

4 End Finish execution

Key Takeaways
●​ Every character in the computer is stored as an integer (ASCII code).​

●​ In C, you can print ASCII using %d.​


●​ In Python, use ord() for ASCII and chr() for reverse mapping.​

●​ Useful for encryption, pattern matching, and encoding-related programs.​

Sample Output:

Enter a character: A

The ASCII value of 'A' is 65

29. Write a Code to Remove All


Characters from a String Except
Alphabets

Definition
This program removes all non-alphabetic characters (such as digits, spaces, punctuation,
and special symbols) from a given string, keeping only the letters A–Z and a–z.

Examples

Input Output Explanation

"He110 W@rld!" "HelWrld" Removed digits and symbols

"123abc!@#XYZ" "abcXYZ" Only alphabets remain


"Good Morning! "GoodMorni Removed spaces, numbers, and
2025" ng" punctuation

✅ The output contains only English alphabets.

Logic Behind the Problem


●​ Each character in a string can be checked individually.​

●​ Using the ASCII range or built-in functions, we can determine whether a character is
alphabetic.​

●​ If it is an alphabet, keep it; otherwise, skip it.​

●​ Finally, form a new string containing only letters.​

ASCII Ranges to Remember

Character Type Range

Uppercase 65–90 (A–Z)


Letters

Lowercase 97–122
Letters (a–z)

So, if​
(ch >= 'A' && ch <= 'Z') or (ch >= 'a' && ch <= 'z') → it’s an alphabet.

Algorithm (Step-by-Step)
1.​ Start​
2.​ Input a string from the user.​

3.​ Create a new empty string to store alphabets only.​

4.​ Traverse each character of the input string.​

5.​ For each character:​

○​ If it’s a letter (A–Z or a–z), add it to the new string.​

○​ Else, skip it.​

6.​ Add a null terminator \0 to mark the end of the new string.​

7.​ Print the new string.​

8.​ End​

Dry Run Example


Input: Hello123!@#World

Ste Character Condition Keep? Resulting


p String

1 H Alphabet ✅ H

2 e Alphabet ✅ He

3 l Alphabet ✅ Hel

4 l Alphabet ✅ Hell

5 o Alphabet ✅ Hello
6 1 Not ❌ -
alphabet

7 2 Not ❌ -
alphabet

8 3 Not ❌ -
alphabet

9 ! Not ❌ -
alphabet

10 @ Not ❌ -
alphabet

11 # Not ❌ -
alphabet

12 W Alphabet ✅ HelloW

13 o Alphabet ✅ HelloWo

14 r Alphabet ✅ HelloWor

15 l Alphabet ✅ HelloWorl

16 d Alphabet ✅ HelloWorld

✅ Output: HelloWorld
C Program
#include <stdio.h>

int main() {

char str[100], result[100];

int i, j = 0;

// Step 1: Take input

printf("Enter a string: ");

gets(str); // Using gets() for simplicity (use fgets() in


modern code)

// Step 2: Traverse each character

for (i = 0; str[i] != '\0'; i++) {

// Step 3: Check if character is an alphabet

if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' &&
str[i] <= 'z')) {

result[j] = str[i]; // Add alphabet to result

j++;

// Step 4: Null-terminate the result string

result[j] = '\0';
// Step 5: Print the cleaned string

printf("String after removing non-alphabet characters: %s\n",


result);

return 0;

Explanation of C Code

Step Description

gets(str) Takes string input from user.

for (i = 0; str[i] != Loops through each character in the


'\0'; i++) string.

(str[i] >= 'A' && str[i] Checks for uppercase letters.


<= 'Z')

(str[i] >= 'a' && str[i] Checks for lowercase letters.


<= 'z')

result[j] = str[i]; Copies valid alphabets to result array.

result[j] = '\0'; Terminates the new string.


printf() Displays final output.

Dry Run of C Code


Input: C0d!ng@123

Character Condition Added Result


?

C Alphabet ✅ C

0 Not ❌ -
alphabet

d Alphabet ✅ Cd

! Not ❌ -
alphabet

n Alphabet ✅ Cdn

g Alphabet ✅ Cdng

@ Not ❌ -
alphabet

1 Not ❌ -
alphabet
2 Not ❌ -
alphabet

3 Not ❌ -
alphabet

✅ Output: Cdng

Python Program
# Step 1: Take input

string = input("Enter a string: ")

# Step 2: Keep only alphabets

result = ""

for ch in string:

if [Link](): # Checks if character is alphabetic

result += ch

# Step 3: Print output

print("String after removing non-alphabet characters:", result)

Short Python Version


s = input("Enter a string: ")

print("".join([ch for ch in s if [Link]()]))


Explanation of Python Code

Step Function / Logic Descriptio


n

input() Takes user input.

isalpha Returns True if the character is alphabetic.


()

join() Joins all valid characters into a single


string.

print() Displays the final string.

Dry Run Example (Python)


Input: A1!b2@C3#

Character isalpha() Result


?

A ✅ A

1 ❌ -
! ❌ -

b ✅ Ab

2 ❌ -

@ ❌ -

C ✅ AbC

3 ❌ -

# ❌ -

✅ Output: AbC

Example Outputs
Example 1

Input: He110 W@rld!

Output: HelWrld

Example 2

Input: 123abc!@#XYZ

Output: abcXYZ
Example 3

Input: G00d M0rn1ng!!!

Output: GdMrnng

Complexity Analysis

Operation Time Complexity Space Explanation


Complexity

Traversing string O(n) O(n) Checks every


character

Filtering alphabets O(1) per - Constant time check


character

Total O(n) O(n) Linear and efficient

Summary of Algorithm

Ste Action Purpose


p

1 Input string Take user input

2 Check Identify alphabets


characters
3 Copy valid ones Form new string

4 Print result Display cleaned string

5 End Finish execution

Key Takeaways
●​ This program filters out digits, spaces, and symbols, keeping only letters.​

●​ In C, you can use ASCII checks.​

●​ In Python, .isalpha() makes the logic simpler.​

●​ Time complexity is O(n), where n is the string length.​

●​ Useful for text cleaning, validation, and preprocessing.​

Sample Output:

Enter a string: He110 W@rld!

String after removing non-alphabet characters: HelWrld

30. Write a Code to Print the Smallest


Element of the Array

Definition
The goal of this program is to find and display the smallest (minimum) element present in
an array.

For example:​
If the array is [8, 3, 5, 1, 9], the smallest element is 1.

Logic Behind the Problem


●​ Every array contains multiple elements.​

●​ The smallest element is the one which has no other element smaller than it.​

●​ To find it, we can:​

1.​ Assume the first element is the smallest.​

2.​ Compare it with every other element.​

3.​ If we find a smaller element, update our smallest value.​

4.​ After checking all elements, print the smallest one.​

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the number of elements n.​

3.​ Input all elements of the array.​

4.​ Initialize min = arr[0] (first element).​

5.​ Loop through the array starting from the second element:​

○​ If arr[i] < min, update min = arr[i].​

6.​ After the loop ends, min contains the smallest value.​

7.​ Print the smallest element.​


8.​ End​

Dry Run Example


Input: [8, 3, 5, 1, 9]

Ste Current Element Current Minimum Condition Updated Minimum


p

Start 8 8 - 8

i=1 3 8 3 < 8 → True 3

i=2 5 3 5 < 3 → False 3

i=3 1 3 1 < 3 → True 1

i=4 9 1 9 < 1 → False 1

✅ Smallest Element = 1

C Program to Find the Smallest Element in an Array


#include <stdio.h>

int main() {

int arr[100], n, i, min;


// Step 1: Input the number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Input the array elements

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Step 3: Assume first element is smallest

min = arr[0];

// Step 4: Traverse and compare

for (i = 1; i < n; i++) {

if (arr[i] < min) {

min = arr[i]; // update smallest value

// Step 5: Print result

printf("The smallest element in the array is: %d\n", min);

return 0;
}

Explanation of C Code

Line / Section Description

int arr[100]; Declares array to store elements.

scanf("%d", Reads total number of elements.


&n);

Input loop Reads each element into arr.

min = arr[0]; Initializes smallest value with first element.

Comparison loop Compares each element with min.

if (arr[i] < Checks if current element is smaller.


min)

min = arr[i]; Updates minimum if smaller found.

Final print Displays the smallest element.

Dry Run of C Code


Input:
Enter number of elements: 5

Enter 5 elements: 8 3 5 1 9

Step-by-Step Execution:

min = 8

Compare 3 < 8 → min = 3

Compare 5 < 3 → no change

Compare 1 < 3 → min = 1

Compare 9 < 1 → no change

✅ Output:
The smallest element in the array is: 1

Python Program
# Step 1: Take input

arr = list(map(int, input("Enter elements separated by space:


").split()))

# Step 2: Assume first element as smallest

min_val = arr[0]

# Step 3: Compare each element

for num in arr:

if num < min_val:


min_val = num

# Step 4: Print smallest element

print("The smallest element in the array is:", min_val)

Short Python Version (Using min() Function)


arr = list(map(int, input("Enter elements: ").split()))

print("The smallest element in the array is:", min(arr))

Explanation of Python Code

Step Description

input().split( Reads multiple numbers from user.


)

map(int, ...) Converts them to integers.

min_val = Initialize smallest element.


arr[0]

Loop through array Compare each number with


min_val.
print() Display smallest number.

Dry Run Example (Python)


Input: 4 9 2 6 1​
Process:

●​ Start with min_val = 4​

●​ Compare 9 → no change​

●​ Compare 2 → update min_val = 2​

●​ Compare 6 → no change​

●​ Compare 1 → update min_val = 1​

✅ Output: The smallest element in the array is: 1

Example Outputs
Example 1

Input: 5 10 2 8 3

Output: The smallest element in the array is: 2

Example 2

Input: -5 -1 -9 0 4

Output: The smallest element in the array is: -9


Complexity Analysis

Operation Time Complexity Space Explanation


Complexity

Traversing array O(n) O(1) Compares each element


once

Initialization O(1) O(1) Constant time

Total O(n) O(1) Linear time, constant space

Summary of Algorithm

Ste Action Purpose


p

1 Input array Get data from user

2 Initialize minimum Start with first element

3 Compare elements Find smaller value

4 Update minimum Track smallest value

5 Print result Display smallest


element
Key Takeaways
●​ The smallest element is found by comparing every element once.​

●​ Simple linear search logic is used.​

●​ Time complexity is O(n) — efficient for all normal arrays.​

●​ In Python, you can use the built-in min() for simplicity.​

●​ In C, a simple for loop does the job.​

Sample Output:

Enter number of elements: 5

Enter 5 elements: 8 3 5 1 9

The smallest element in the array is: 1

31. Write a Code to Reverse the


Elements of the Array

Definition
Reversing an array means rearranging its elements in opposite order — the first element
becomes the last, the second becomes second last, and so on.

For example:​
If the array is [1, 2, 3, 4, 5],​
the reversed array will be [5, 4, 3, 2, 1].

Logic Behind the Problem


●​ Arrays store data sequentially in memory.​

●​ To reverse an array, we can swap elements from both ends:​

○​ Swap the first and last,​

○​ Swap the second and second-last,​

○​ Continue until the middle of the array is reached.​

This ensures all elements are reversed efficiently.

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the number of elements n.​

3.​ Input all array elements.​

4.​ Initialize two pointers:​

○​ start = 0​

○​ end = n - 1​

5.​ While start < end:​

○​ Swap arr[start] and arr[end].​

○​ Increment start and decrement end.​

6.​ After loop ends, array will be reversed.​

7.​ Display the reversed array.​

8.​ End​

Dry Run Example


Input: [10, 20, 30, 40, 50]

Ste start en Elements Resulting Array


p d Swapped

1 0 4 10 ↔ 50 [50, 20, 30, 40, 10]

2 1 3 20 ↔ 40 [50, 40, 30, 20, 10]

3 2 2 Middle reached [50, 40, 30, 20, 10]

✅ Final Output: [50, 40, 30, 20, 10]

C Program to Reverse the Elements of an Array


#include <stdio.h>

int main() {

int arr[100], n, start, end, temp;

// Step 1: Input number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Input array elements

printf("Enter %d elements: ", n);

for (int i = 0; i < n; i++) {


scanf("%d", &arr[i]);

// Step 3: Initialize pointers

start = 0;

end = n - 1;

// Step 4: Reverse the array by swapping

while (start < end) {

temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

// Step 5: Print reversed array

printf("Reversed array: ");

for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");
return 0;

Explanation of C Code

Step Description

arr[100] Declares array to store up to 100 integers.

Input loop Takes user input for array elements.

start = 0, end = Initialize pointers for swapping.


n-1

while (start < Continue swapping until middle reached.


end)

Swap logic Uses a temporary variable temp to exchange


elements.

Final print Displays reversed array after all swaps.

Dry Run of C Code


Input:

Enter number of elements: 5

Enter 5 elements: 10 20 30 40 50
Execution Steps:

start = 0, end = 4 → swap 10 & 50

start = 1, end = 3 → swap 20 & 40

start = 2, end = 2 → stop

✅ Output:
Reversed array: 50 40 30 20 10

Python Program to Reverse the Array


# Step 1: Take input from user

arr = list(map(int, input("Enter elements separated by space:


").split()))

# Step 2: Reverse using two-pointer method

start = 0

end = len(arr) - 1

while start < end:

arr[start], arr[end] = arr[end], arr[start] # Swap elements

start += 1

end -= 1

# Step 3: Print reversed array


print("Reversed array:", arr)

Short Python Version (Using Slicing)


arr = list(map(int, input("Enter elements: ").split()))

print("Reversed array:", arr[::-1])

Explanation of Python Code

Step Description

input().split() Reads all elements as strings.

map(int, ...) Converts them to integers.

start, end Index pointers for swapping.

arr[start], arr[end] = arr[end], Python’s simultaneous swap.


arr[start]

arr[::-1] Built-in slicing method to reverse.

Dry Run Example (Python)


Input: 5 10 15 20
Process:

start = 0, end = 3 → swap 5 & 20 → [20, 10, 15, 5]

start = 1, end = 2 → swap 10 & 15 → [20, 15, 10, 5]

✅ Output: [20, 15, 10, 5]

Example Outputs
Example 1

Input: 1 2 3 4 5

Output: Reversed array: 5 4 3 2 1

Example 2

Input: 10 20 30

Output: Reversed array: 30 20 10

Complexity Analysis

Operation Time Space Explanation


Complexity Complexity

Swapping elements O(n) O(1) Each element swapped


once

Using slicing O(n) O(n) Creates a new reversed


(Python) list
Overall O(n) O(1) Linear time, constant
space

Summary of Algorithm

Ste Action Purpose


p

1 Input array Get user data

2 Initialize pointers Start and end


positions

3 Swap elements Reverse in-place

4 Print result Display reversed array

Key Takeaways
●​ Reversing can be done using two-pointer swapping or built-in functions.​

●​ It requires O(n) time and O(1) extra space.​

●​ Works efficiently for both small and large arrays.​

Sample Output:

Enter number of elements: 5

Enter 5 elements: 10 20 30 40 50
Reversed array: 50 40 30 20 10

32. Write a Code to Sort the Elements of


an Array

Definition
Sorting means arranging elements of an array in a specific order — usually ascending
(smallest to largest).​
Sorting helps in organizing data so that searching and other operations become faster and
easier.

We’ll explore five popular sorting methods:

1.​ Bubble Sort​

2.​ Selection Sort​

3.​ Insertion Sort​

4.​ Merge Sort​

5.​ Quick Sort​

1. Bubble Sort

Logic

●​ Imagine bubbles rising in water — the largest bubble reaches the top first.​

●​ Similarly, in each pass, the largest element moves to the end of the array.​

●​ The process repeats until all elements are sorted.​


Algorithm (Step-by-Step)

1.​ Start​

2.​ Input number of elements and store them in an array.​

3.​ For each element in the array:​

○​ Compare each pair of adjacent elements.​

○​ If the first element is greater than the second, swap them.​

4.​ Repeat until the array is sorted.​

5.​ Print the sorted array.​

6.​ End​

C Program (Bubble Sort)

#include <stdio.h>

int main() {

int arr[100], n, i, j, temp;

printf("Enter number of elements: ");

scanf("%d", &n);

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

}
// Bubble Sort Logic

for (i = 0; i < n - 1; i++) {

for (j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) { // Compare adjacent elements

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp; // Swap if needed

printf("Sorted array using Bubble Sort: ");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

Example (Dry Run)

Input: 5 3 8 1 4
Pass 1: Compare pairs → [3, 5, 1, 4, 8]​
Pass 2: [3, 1, 4, 5, 8]​
Pass 3: [1, 3, 4, 5, 8]​
Final Sorted Array: 1 3 4 5 8

Concept Summary

Bubble Sort is simple but slow for large arrays since it keeps swapping until all elements are
in order.​
Best for small datasets and for learning basic sorting logic.

2. Selection Sort

Logic

●​ Think of selecting the smallest number from a group and putting it in the first position.​

●​ In each pass:​

○​ Find the smallest element in the unsorted part of the array.​

○​ Place it in its correct position (front).​

Algorithm (Step-by-Step)

1.​ Start​

2.​ Input array elements.​

3.​ For each position i in the array:​

○​ Find the smallest element in the unsorted part (from i to end).​

○​ Swap it with the element at i.​

4.​ Print the sorted array.​


5.​ End​

C Program (Selection Sort)

#include <stdio.h>

int main() {

int arr[100], n, i, j, min_idx, temp;

printf("Enter number of elements: ");

scanf("%d", &n);

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Selection Sort Logic

for (i = 0; i < n - 1; i++) {

min_idx = i; // Assume current position has smallest


element

for (j = i + 1; j < n; j++) {

if (arr[j] < arr[min_idx]) {

min_idx = j; // Update index if smaller found

}
}

// Swap smallest element with the first element of unsorted


part

temp = arr[i];

arr[i] = arr[min_idx];

arr[min_idx] = temp;

printf("Sorted array using Selection Sort: ");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

Example

Input: 5 3 8 1 4

Step 1: Find min (1), swap with 5 → [1, 3, 8, 5, 4]​


Step 2: Find min (3), no swap → [1, 3, 8, 5, 4]​
Step 3: Find min (4), swap with 8 → [1, 3, 4, 5, 8]​
Sorted Output: 1 3 4 5 8
Concept Summary

Selection Sort repeatedly finds the smallest element and places it in correct order.​
It’s simple but not very efficient for large lists.

3. Insertion Sort

Logic

●​ Like arranging cards in your hand.​

●​ Pick one card at a time and insert it into the correct position among the already
sorted cards.​

Algorithm (Step-by-Step)

1.​ Start​

2.​ Input array elements.​

3.​ Assume first element is already sorted.​

4.​ For each next element:​

○​ Compare it with previous elements.​

○​ Shift all larger elements one position to the right.​

○​ Insert the element in the correct place.​

5.​ Print the sorted array.​

6.​ End​

C Program (Insertion Sort)

#include <stdio.h>
int main() {

int arr[100], n, i, j, key;

printf("Enter number of elements: ");

scanf("%d", &n);

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Insertion Sort Logic

for (i = 1; i < n; i++) {

key = arr[i];

j = i - 1;

// Move elements greater than key one position ahead

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = key; // Insert key in correct position

}
printf("Sorted array using Insertion Sort: ");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

Example

Input: 5 3 8 1 4

Ste Current Key Action Resulting Array


p

1 3 Insert before 5 [3, 5, 8, 1, 4]

2 8 No change [3, 5, 8, 1, 4]

3 1 Shift 8, 5, 3 → Insert 1 [1, 3, 5, 8, 4]

4 4 Shift 8, 5 → Insert 4 [1, 3, 4, 5, 8]

✅ Final Sorted Array: 1 3 4 5 8


Concept Summary

Insertion Sort works best when the array is almost sorted.​


It is simple and efficient for small or partially sorted data.

4. Merge Sort

Logic

●​ Merge Sort is a Divide and Conquer algorithm.​

●​ It divides the array into two halves, sorts them separately, and then merges them
together in sorted order.​

Concept

1.​ Divide: Split the array into two halves.​

2.​ Conquer: Sort each half recursively.​

3.​ Combine: Merge the two sorted halves into one sorted array.​

Algorithm (Step-by-Step)

1.​ Start​

2.​ If the array has one element, it’s already sorted.​

3.​ Divide the array into two halves.​

4.​ Recursively apply merge sort to both halves.​

5.​ Merge the two halves in sorted order.​

6.​ End​
C Program (Merge Sort)

#include <stdio.h>

void merge(int arr[], int left, int mid, int right) {

int i = left, j = mid + 1, k = 0;

int temp[100];

// Merge two sorted halves

while (i <= mid && j <= right) {

if (arr[i] <= arr[j])

temp[k++] = arr[i++];

else

temp[k++] = arr[j++];

while (i <= mid)

temp[k++] = arr[i++];

while (j <= right)

temp[k++] = arr[j++];

// Copy back to original array

for (i = left, j = 0; i <= right; i++, j++)

arr[i] = temp[j];
}

void mergeSort(int arr[], int left, int right) {

if (left < right) {

int mid = (left + right) / 2;

mergeSort(arr, left, mid); // Sort left half

mergeSort(arr, mid + 1, right); // Sort right half

merge(arr, left, mid, right); // Merge halves

int main() {

int arr[100], n, i;

printf("Enter number of elements: ");

scanf("%d", &n);

printf("Enter %d elements: ", n);

for (i = 0; i < n; i++)

scanf("%d", &arr[i]);

mergeSort(arr, 0, n - 1);

printf("Sorted array using Merge Sort: ");


for (i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");

return 0;

Example

Input: 5 3 8 1 4

Divide into: [5,3,8] and [1,4]​


→ Sort [5,3,8] → [3,5,8]​
→ Sort [1,4] → [1,4]​
→ Merge [3,5,8] and [1,4] → [1,3,4,5,8]

✅ Sorted Array: 1 3 4 5 8

Concept Summary

Merge Sort is very efficient and suitable for large datasets.​


It uses recursion and merging to sort elements.

5. Quick Sort

Logic

●​ Quick Sort also uses Divide and Conquer.​

●​ It picks one element as a pivot, then:​


○​ Places smaller elements to the left,​

○​ Larger elements to the right.​

●​ Recursively sorts both sides.​

Algorithm (Step-by-Step)

1.​ Start​

2.​ Choose a pivot element (usually the last element).​

3.​ Rearrange the array so all smaller elements come before the pivot and larger ones
after.​

4.​ Recursively apply the same process to both sides of the pivot.​

5.​ End​

C Program (Quick Sort)

#include <stdio.h>

void swap(int *a, int *b) {

int temp = *a;

*a = *b;

*b = temp;

int partition(int arr[], int low, int high) {

int pivot = arr[high];

int i = low - 1;
for (int j = low; j < high; j++) {

if (arr[j] < pivot) {

i++;

swap(&arr[i], &arr[j]);

swap(&arr[i + 1], &arr[high]);

return i + 1;

void quickSort(int arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

int main() {

int arr[100], n, i;

printf("Enter number of elements: ");

scanf("%d", &n);
printf("Enter %d elements: ", n);

for (i = 0; i < n; i++)

scanf("%d", &arr[i]);

quickSort(arr, 0, n - 1);

printf("Sorted array using Quick Sort: ");

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");

return 0;

Example

Input: 5 3 8 1 4

Pivot = 4​
→ Smaller: [3,1], Larger: [5,8]​
→ Sort each part recursively → [1,3,4,5,8]

✅ Final Sorted Array: 1 3 4 5 8

Concept Summary
Quick Sort is very fast and efficient for large datasets.​
It works by choosing a pivot and dividing the array around it.​
Unlike Merge Sort, it sorts “in place” — meaning no extra space is used.

Final Comparison (Conceptual


Summary)
Sorting Concept Summary When to Use
Method

Bubble Sort Compares and swaps adjacent Simple learning, small arrays
elements

Selection Sort Finds smallest and places in correct Easy to understand, few swaps
spot

Insertion Sort Builds sorted list one by one Nearly sorted or small datasets

Merge Sort Divides and merges sorted halves Large datasets, stable sorting

Quick Sort Uses pivot to divide and sort in place Large datasets, fastest on
average

Example Input and Output

Input:

Enter number of elements: 5

Enter 5 elements: 5 3 8 1 4
Output (for all methods):

Sorted array using Bubble Sort: 1 3 4 5 8

Sorted array using Selection Sort: 1 3 4 5 8

Sorted array using Insertion Sort: 1 3 4 5 8

Sorted array using Merge Sort: 1 3 4 5 8

Sorted array using Quick Sort: 1 3 4 5 8

33. Write a Code to Sort the Elements of


the Array Without Using Sort Method

Definition
Sorting means arranging elements in a specific order — usually ascending (smallest to
largest).

Here, we are not allowed to use any built-in sort function like sort() in Python or
libraries in C.​
So, we will manually sort the array using logical comparisons and swapping techniques
— similar to Bubble Sort logic.

Logic Behind the Program


●​ The main idea is to compare each element with every other element.​

●​ If one element is smaller than the other, we swap them to bring them into the correct
order.​

●​ Repeating this process ensures that all elements end up in ascending order.​

We will implement this using nested loops — an outer loop for the passes and an inner
loop for comparing elements.
Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the number of elements n and the array elements.​

3.​ Use two loops:​

○​ Outer Loop: Runs from the first element to the second-last element.​

○​ Inner Loop: Compares the current element with all elements that come after
it.​

4.​ If arr[i] > arr[j], swap the two elements.​

5.​ Repeat until the entire array is sorted.​

6.​ Print the sorted array.​

7.​ End​

C Program to Sort Array Without Using Sort Method


#include <stdio.h>

int main() {

int arr[100], n, i, j, temp;

// Step 1: Input number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Input array elements

printf("Enter %d elements: ", n);


for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Step 3: Sorting logic (without using sort function)

for (i = 0; i < n - 1; i++) {

for (j = i + 1; j < n; j++) {

if (arr[i] > arr[j]) { // Compare elements

temp = arr[i]; // Swap if they are in wrong


order

arr[i] = arr[j];

arr[j] = temp;

// Step 4: Print sorted array

printf("Sorted array in ascending order: ");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

}
Explanation of the C Code

Ste Description
p

1 The user enters how many elements the array has.

2 All elements are read and stored in an array.

3 Two loops are used — the outer loop tracks passes, and the inner loop compares
elements.

4 Whenever arr[i] > arr[j], it swaps the two values to bring them into order.

5 The process continues until the array is sorted in ascending order.

Example (Dry Run)


Input:

n = 5

Elements = 5 2 8 1 4

Pass 1 (i = 0):

●​ Compare 5 and 2 → swap → [2, 5, 8, 1, 4]​

●​ Compare 5 and 8 → no swap​


●​ Compare 5 and 1 → swap → [2, 1, 8, 5, 4]​

●​ Compare 2 and 4 → no swap​

Pass 2 (i = 1):

●​ Compare 5 and 8 → no swap​

●​ Compare 5 and 1 → swap → [2, 1, 8, 5, 4]​

Pass 3 (i = 2):

●​ Compare and swap accordingly → [1, 2, 4, 5, 8]​

✅ Final Sorted Array: [1, 2, 4, 5, 8]

Logic Summary
This method works like basic comparison sorting:

●​ Each element is compared with every other element that comes after it.​

●​ Whenever two elements are out of order, they are swapped.​

●​ After enough passes, the array becomes sorted.​

Python Program to Sort Array Without Using sort()


# Step 1: Take input

n = int(input("Enter number of elements: "))

arr = []

# Step 2: Input array elements

print("Enter elements:")
for i in range(n):

[Link](int(input()))

# Step 3: Sorting logic (without using sort())

for i in range(n - 1):

for j in range(i + 1, n):

if arr[i] > arr[j]: # Compare elements

arr[i], arr[j] = arr[j], arr[i] # Swap if needed

# Step 4: Print sorted array

print("Sorted array in ascending order:")

for i in arr:

print(i, end=" ")

Explanation of Python Code


●​ Input section: Takes the number of elements and the elements themselves.​

●​ Two nested loops: Compare all elements pair by pair.​

●​ Condition: If one element is greater than another, they are swapped.​

●​ Output: Finally, it prints the sorted array in ascending order.​

Example Input and Output


Input:
Enter number of elements: 5

Enter elements:

Output:

Sorted array in ascending order:

1 2 4 5 8

Detailed Conceptual Explanation


This sorting logic is based on element comparison and swapping:

●​ Each time through the loop, the smallest unsorted element “moves” toward the front.​

●​ It’s similar to Bubble Sort or Selection Sort, but implemented manually.​

●​ It doesn’t rely on library functions — only on conditional checks and swaps.​

●​ Works well for small arrays or when learning sorting concepts.​

Summary of the Program

Ste Action Purpose


p
1 Take input of array size and To get user data
elements

2 Compare each pair of elements To find incorrect order

3 Swap if needed To place smaller elements


first

4 Repeat until all elements are in order Complete the sorting

5 Print the sorted array Show result

✅ Final Output Example


Enter number of elements: 5

Enter elements: 5 2 8 1 4

Sorted array in ascending order: 1 2 4 5 8

Write a Code to Replace a Substring in


34.

a String

Definition
A substring is a sequence of characters that appears within another string.​
This program replaces all occurrences of a given substring inside a main string with another
substring.

Example:

Input String: "I like apples"


Substring to replace: "apples"

New substring: "mangoes"

Output: "I like mangoes"

Logic Behind the Program


The logic is to:

1.​ Take the original string.​

2.​ Take the substring that needs to be replaced.​

3.​ Take the new substring to insert in its place.​

4.​ Replace all occurrences of the old substring with the new one.​

5.​ Display the modified string.​

We can achieve this by scanning the original string and rebuilding a new one where every
occurrence of the old substring is replaced with the new substring.

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the main string.​

3.​ Input the substring to be replaced.​

4.​ Input the new substring.​

5.​ Search the main string for occurrences of the old substring.​

6.​ Whenever found, replace it with the new substring.​

7.​ Store and print the final modified string.​


8.​ End​

C Program to Replace a Substring in a String


#include <stdio.h>

#include <string.h>

int main() {

char str[200], oldSub[50], newSub[50], result[300];

int i, j = 0, k, flag = 0;

// Step 1: Take input

printf("Enter the main string: ");

gets(str);

printf("Enter the substring to replace: ");

gets(oldSub);

printf("Enter the new substring: ");

gets(newSub);

// Step 2: Initialize the result string

result[0] = '\0';

// Step 3: Replace substring logic


for (i = 0; str[i] != '\0'; i++) {

flag = 1;

// Check if substring matches

for (k = 0; oldSub[k] != '\0'; k++) {

if (str[i + k] != oldSub[k]) {

flag = 0;

break;

// If match found, copy newSub to result

if (flag == 1) {

strcat(result, newSub);

i += k - 1; // Move index ahead

} else {

// Copy one character at a time

strncat(result, &str[i], 1);

// Step 4: Print the modified string

printf("Modified String: %s\n", result);


return 0;

Explanation of the C Code

Ste Description
p

1 The program reads three inputs: main string, old substring, and new substring.

2 A result string is used to store the modified version.

3 The program checks each position of the main string for a match with the old
substring.

4 If a match is found, the new substring is copied into the result.

5 If no match is found, the current character is copied as it is.

6 The final result string is printed as the modified output.

Example (Dry Run)


Input:

Main String: I love apples

Substring to replace: apples

New Substring: mangoes


Process:

●​ Starts scanning: “I love apples”​

●​ Finds “apples” at position 7​

●​ Replaces it with “mangoes”​

✅ Output:
Modified String: I love mangoes

Logic Summary
The logic revolves around pattern matching:

●​ Every character of the main string is checked.​

●​ When a substring match occurs, the new substring is inserted.​

●​ All other characters are copied unchanged.​

●​ The final result is a fully modified string with all replacements done.​

Python Program to Replace a Substring in a String


# Step 1: Take input

main_str = input("Enter the main string: ")

old_sub = input("Enter the substring to replace: ")

new_sub = input("Enter the new substring: ")

# Step 2: Replace substring using replace() method


modified_str = main_str.replace(old_sub, new_sub)

# Step 3: Print modified string

print("Modified String:", modified_str)

Explanation of Python Code

Ste Function Description


p

1 input() Takes user input for all strings.

2 replace Replaces all occurrences of the old substring with the new
() one.

3 print() Displays the modified string.

Example Input and Output


Input:

Enter the main string: The sky is blue

Enter the substring to replace: blue

Enter the new substring: clear

Output:

Modified String: The sky is clear


Detailed Conceptual Explanation
The substring replacement process is based on string searching and reconstruction:

●​ Each substring has a starting and ending index.​

●​ The algorithm compares the substring from the main string and identifies matches.​

●​ Every time it finds the substring, it rebuilds the main string by combining parts of the
old string with the new substring.​

●​ This ensures all occurrences are updated in the result.​

In Python, this is handled internally by the replace() function, which performs these
operations efficiently.

Summary of Algorithm

Ste Action Purpose


p

1 Take input Get all required strings

2 Search for substring Identify parts to be


replaced

3 Replace with new Modify the main string


substring

4 Display output Show the updated string


✅ Final Output Example
Enter the main string: I love apples

Enter the substring to replace: apples

Enter the new substring: mangoes

Modified String: I love mangoes

35. Write a Code to Remove Spaces from


a String

Definition
A string is a collection of characters that may include letters, digits, punctuation, and
spaces.​
In this program, we aim to remove all spaces from the given string — that is, eliminate any
' ' characters that appear between or around words.

Example:

Input:

"Hello World from ChatGPT"

Output:

"HelloWorldfromChatGPT"

This means all spaces between words are removed, and only the characters remain.

Logic Behind the Program


The logic is very simple:

1.​ Take an input string from the user.​

2.​ Create a new string to store the result.​

3.​ Go through each character of the original string:​

○​ If the character is not a space, copy it to the new string.​

○​ If it is a space, skip it.​

4.​ Display the new string without spaces.​

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input a string from the user.​

3.​ Initialize an empty result string.​

4.​ Loop through each character of the input string.​

5.​ If the character is not a space ' ', add it to the result string.​

6.​ After the loop ends, print the result string.​

7.​ End​

C Program to Remove Spaces from a String


#include <stdio.h>

#include <string.h>

int main() {

char str[200], result[200];


int i, j = 0;

// Step 1: Take input

printf("Enter a string: ");

gets(str);

// Step 2: Loop through each character

for (i = 0; str[i] != '\0'; i++) {

if (str[i] != ' ') { // Step 3: Check if it's not a space

result[j++] = str[i];

result[j] = '\0'; // Step 4: End the result string

// Step 5: Print the new string

printf("String without spaces: %s\n", result);

return 0;

Explanation of the C Code


Ste Description
p

1 The user inputs a string.

2 We scan the string character by character.

3 Every time a non-space character is found, it is copied to the new string


result.

4 Spaces are skipped — not copied.

5 After copying, a null character ('\0') marks the end of the new string.

6 The result is printed — a string with all spaces removed.

Example (Dry Run)


Input:

"Hello World"

Process:

Ste Character Space Result


p ?

1 H No H
2 e No He

3 l No Hel

4 l No Hell

5 o No Hello

6 (space) Yes skip

7 W No HelloW

8 o No HelloWo

9 r No HelloWor

10 l No HelloWorl

11 d No HelloWorld

✅ Output:
HelloWorld

Logic Summary
The key idea is:
●​ Copy only non-space characters.​

●​ Skip any ' ' character.​

●​ Build a clean, compact string as a result.​

This logic ensures all spaces—leading, trailing, or between words—are removed.

Python Program to Remove Spaces from a String


# Step 1: Take input

string = input("Enter a string: ")

# Step 2: Remove spaces using replace() method

no_space_string = [Link](" ", "")

# Step 3: Print result

print("String without spaces:", no_space_string)

Explanation of Python Code

Ste Function Description


p

1 input() Reads the string from the user.

2 replace(" ", Replaces every space with an empty


"") string.
3 print() Displays the new string without spaces.

Example Input and Output

Input:

Enter a string: Hello World from Python

Output:

String without spaces: HelloWorldfromPython

Alternative Python Approach (Without replace())


You can also do it manually (similar to the C version):

string = input("Enter a string: ")

result = ""

for ch in string:

if ch != " ": # Skip spaces

result += ch

print("String without spaces:", result)

Detailed Conceptual Explanation


In strings, a space ' ' is just another character, so:

●​ The removal process means building a new string where spaces are excluded.​

●​ This is done by iterating and selectively adding characters that aren’t spaces.​

●​ The concept helps in text-cleaning operations, especially in preprocessing input data,


formatting output, or working with user-entered strings.​

Summary of Algorithm

Ste Action Purpose


p

1 Take input Read a string from the user

2 Loop through Check each one individually


characters

3 Skip spaces Don’t copy spaces

4 Form new string Store only valid characters

5 Display output Show string without spaces

✅ Final Output Example


Enter a string: The quick brown fox

String without spaces: Thequickbrownfox


36. Write a Code to Count Inversions in
an Array

Definition
An inversion in an array is a pair of elements (a[i], a[j]) such that:

●​ i < j, and​

●​ a[i] > a[j].​

It represents how unsorted an array is.​


If the array is already sorted in ascending order, there will be zero inversions.​
If it’s in reverse order, it will have the maximum number of inversions.

Example:

Input:

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

Inversion pairs:

●​ (2, 1)​

●​ (4, 1)​

●​ (4, 3)​

Total Inversions = 3

Logic Behind the Program


The main idea is:
1.​ Compare every element with every other element that comes after it.​

2.​ If the first element is greater than the second one, that’s an inversion.​

3.​ Keep counting such pairs.​

This can be done using:

●​ A simple nested loop (basic method)​

●​ Or using merge sort (optimized method).​

Here, we’ll understand both, starting with the simpler approach.

Algorithm (Simple Method – Step-by-Step)


1.​ Start​

2.​ Input the number of elements n and the array elements.​

3.​ Initialize a variable count = 0.​

4.​ For every element i in the array:​

○​ Compare it with every other element j that comes after it.​

○​ If arr[i] > arr[j], increment count.​

5.​ After checking all pairs, print count.​

6.​ End​

C Program to Count Inversions (Simple Nested Loop


Method)
#include <stdio.h>
int main() {

int arr[100], n, i, j, count = 0;

// Step 1: Input number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Step 2: Input array elements

printf("Enter array elements: ");

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Step 3: Compare each pair (i, j)

for (i = 0; i < n - 1; i++) {

for (j = i + 1; j < n; j++) {

if (arr[i] > arr[j]) { // Step 4: Check inversion

count++;

// Step 5: Display result

printf("Total number of inversions: %d\n", count);


return 0;

Explanation of the C Code

Ste Description
p

1 Read the array size and elements.

2 Initialize a counter variable to 0.

3 Use two nested loops — the outer loop for the first element, and the inner loop for
the second.

4 If arr[i] > arr[j], it’s an inversion — increase the count.

5 Print the total inversion count after all comparisons.

Example (Dry Run)


Input:

n = 5

arr = [2, 4, 1, 3, 5]
Comparisons:

Pair Condition Inversion


?

(2, 4) 2 > 4? No

(2, 1) 2 > 1? Yes

(4, 1) 4 > 1? Yes

(4, 3) 4 > 3? Yes

(3, 5) 3 > 5? No

✅ Total Inversions = 3

Python Program to Count Inversions (Simple


Approach)
# Step 1: Input

n = int(input("Enter number of elements: "))

arr = []

print("Enter array elements:")

for i in range(n):

[Link](int(input()))
# Step 2: Count inversions

count = 0

for i in range(n - 1):

for j in range(i + 1, n):

if arr[i] > arr[j]:

count += 1

# Step 3: Print result

print("Total number of inversions:", count)

Explanation of Python Code

Ste Function Description


p

1 input() Reads array size and elements.

2 Nested loops Compare each pair (i, j) where i <


j.

3 if arr[i] > Checks if the order is inverted.


arr[j]:

4 count += 1 Increments inversion count.

5 Print final count.


Example Input and Output
Input:

Enter number of elements: 5

Enter array elements: 2 4 1 3 5

Output:

Total number of inversions: 3

Alternative Concept: Using Merge Sort Logic


(Conceptual Overview)
The merge sort method can also count inversions efficiently while sorting the array.

Idea:

During the merge step, whenever an element from the right subarray is placed before one
from the left, it means there are inversions equal to the remaining elements in the left
subarray.

For example:

Left = [2, 4, 6]

Right = [1, 5]

When merging:

●​ 1 comes before 2 → 3 inversions (because 1 < all of 2,4,6)​

●​ 5 comes before 6 → 1 inversion​


✅Total = 4 inversions​
This logic is used to count inversions efficiently while sorting.

Conceptual Explanation (Merge Sort Logic)


1.​ Divide the array into two halves.​

2.​ Recursively count inversions in each half.​

3.​ Count additional inversions that occur across the two halves while merging.​

4.​ Sum them all up.​

This is much faster but conceptually more advanced.​


The simple version (nested loop) is best for learning the concept before moving to
merge-based logic.

Logic Summary

Concept Meaning

Inversion A pair where an earlier element is greater than a later


one

Purpose Measures how unsorted the array is

Simple Method Compare all pairs using nested loops

Merge Sort Method Count inversions while sorting the array

Summary of Algorithm
Ste Action Purpose
p

1 Take input Read array size and


elements

2 Compare pairs Find where order is reversed

3 Increment Track inversion occurrences


count

4 Output count Display total inversions

✅ Final Example Output


Enter number of elements: 5

Enter array elements: 2 4 1 3 5

Total number of inversions: 3

37. Write a Program to Find the Power of


a Number

Definition
The power of a number represents repeated multiplication of a number by itself.​
If a number is raised to an exponent, it means multiplying that number by itself the given
number of times.

Mathematically:
ab=a×a×a×…(b times)a^b = a \times a \times a \times \ldots \text{(b times)}ab=a×a×a×…(b
times)

Example:

Input:

Base = 2

Exponent = 3

Calculation:

23=2×2×2=82^3 = 2 × 2 × 2 = 823=2×2×2=8

Output:

Result = 8

Logic Behind the Program


To calculate the power of a number:

1.​ We take two inputs — the base and the exponent.​

2.​ Initialize a variable result to 1.​

3.​ Multiply result by base repeatedly exponent times.​

4.​ Finally, print the result.​

We can also calculate it using the built-in pow() function, but here we’ll understand both the
manual logic and function-based approach.

Algorithm (Manual Multiplication Method –


Step-by-Step)
1.​ Start​

2.​ Input the base number and exponent.​

3.​ Initialize result = 1.​

4.​ Repeat multiplication exponent times:​

○​ result = result * base​

5.​ Print the final value of result.​

6.​ End​

C Program to Find Power of a Number (Without Using


pow())
#include <stdio.h>

int main() {

double base, result = 1.0;

int exponent, i;

// Step 1: Take input

printf("Enter the base number: ");

scanf("%lf", &base);

printf("Enter the exponent: ");

scanf("%d", &exponent);
// Step 2: Multiply base exponent times

for (i = 1; i <= exponent; i++) {

result = result * base;

// Step 3: Display result

printf("Result = %.2lf\n", result);

return 0;

Explanation of the C Code

Ste Description
p

1 The user inputs the base and exponent values.

2 The variable result is initialized to 1.

3 A loop runs from 1 to the exponent value, multiplying the result by the base each
time.

4 After all multiplications, the final power value is printed.


Example (Dry Run)
Input:

Base = 3

Exponent = 4

Process:

Ste Multiplication Result


p

1 1×3 3

2 3×3 9

3 9×3 27

4 27 × 3 81

✅ Output:
Result = 81.00

Alternate C Program (Using pow() Function)


#include <stdio.h>

#include <math.h>

int main() {
double base, result;

int exponent;

// Step 1: Take input

printf("Enter base: ");

scanf("%lf", &base);

printf("Enter exponent: ");

scanf("%d", &exponent);

// Step 2: Calculate using pow()

result = pow(base, exponent);

// Step 3: Display result

printf("Result = %.2lf\n", result);

return 0;

Explanation of pow() Method


●​ The function pow(base, exponent) is available in <math.h>.​

●​ It directly returns the value of base raised to the power of exponent.​


●​ Example: pow(2, 3) returns 8.​

Python Program to Find Power of a Number


Method 1 – Using Manual Calculation

# Step 1: Take input

base = float(input("Enter the base number: "))

exponent = int(input("Enter the exponent: "))

# Step 2: Initialize result

result = 1

# Step 3: Multiply base exponent times

for i in range(exponent):

result *= base

# Step 4: Print result

print("Result =", result)

Method 2 – Using Built-in Operator

In Python, you can also use the exponentiation operator (**) or the pow() function.

base = float(input("Enter base: "))

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


# Using ** operator

result = base ** exponent

print("Result =", result)

Explanation of Python Code

Ste Description
p

1 User enters base and exponent values.

2 Either a loop or the ** operator is used to find the


power.

3 The final computed result is printed.

Example Input and Output


Input:

Enter base: 2

Enter exponent: 5

Output:

Result = 32.0
Detailed Conceptual Explanation
When we say aba^bab, it means:

●​ Multiply a by itself b times.​

●​ If b = 0, the result is always 1, since any number to the power of 0 equals 1.​

●​ If b is negative, the power becomes 1 / (a^|b|).​

For example:

2^-3 = 1 / (2^3) = 1 / 8 = 0.125

This concept applies equally in both C and Python.

Logic Summary

Concept Description

Base The number to be multiplied

Exponent The number of times the base is


multiplied

Manual Method Repeated multiplication using a loop

Built-in Method Use pow() or exponent operator


Summary of Algorithm

Ste Action Purpose


p

1 Take input of base and Get numbers from user


exponent

2 Initialize result as 1 Starting point for multiplication

3 Multiply repeatedly Compute power manually

4 Display result Show final computed value

✅ Final Output Example


Enter base: 3

Enter exponent: 4

Result = 81.0

41. Write a Program to Add Two


Fractions

Definition
Adding two fractions means computing the sum of two rational numbers ab\frac{a}{b}ba​and
cd\frac{c}{d}dc​.​
The result is another fraction pq\frac{p}{q}qp​, which is usually reduced to lowest terms.

Basic formula using LCM of denominators:

ab+cd=a×(L/b)+c×(L/d)L\frac{a}{b} + \frac{c}{d} = \frac{a \times (L/b) + c \times


(L/d)}{L}ba​+dc​=La×(L/b)+c×(L/d)​

where L=lcm(b,d)L = \text{lcm}(b, d)L=lcm(b,d).​


After computing numerator and denominator, simplify by dividing both by their GCD.

Logic (Plain English)


1.​ Read two fractions (numerator and denominator for each).​

2.​ Validate denominators are not zero.​

3.​ Find the least common multiple (LCM) of the two denominators to get a common
denominator.​

4.​ Convert each fraction to the common denominator and add numerators.​

5.​ Simplify the resulting fraction by dividing numerator and denominator by their
greatest common divisor (GCD).​

6.​ Ensure the denominator is positive (move any sign to the numerator).​

7.​ Print the simplified result (optionally as an improper fraction and/or mixed number).​

Step-by-Step Algorithm
1.​ Input: n1, d1 (first fraction), n2, d2 (second fraction).​

2.​ If d1 == 0 or d2 == 0 → print error and exit.​

3.​ Compute g = gcd(d1, d2).​

4.​ Compute lcm = (d1 / g) * d2.​

5.​ Compute sum_num = n1 * (lcm / d1) + n2 * (lcm / d2).​


6.​ sum_den = lcm.​

7.​ Compute g2 = gcd(abs(sum_num), abs(sum_den)).​

8.​ sum_num /= g2; sum_den /= g2.​

9.​ If sum_den < 0: sum_den = -sum_den; sum_num = -sum_num.​

10.​Output sum_num / sum_den. Optionally compute mixed number: whole =


sum_num / sum_den, rem = abs(sum_num % sum_den).​

Dry Run Example


Add 12+13\frac{1}{2} + \frac{1}{3}21​+31​.

1.​ g = gcd(2,3) = 1​

2.​ lcm = (2/1)*3 = 6​

3.​ sum_num = 1*(6/2) + 1*(6/3) = 3 + 2 = 5​

4.​ sum_den = 6​

5.​ g2 = gcd(5,6) = 1 → simplified fraction = 5/6.​

Output: 5/6.

C Program (Complete, safe, commented)


#include <stdio.h>

#include <stdlib.h>

long long gcd(long long a, long long b) {

if (a < 0) a = -a;
if (b < 0) b = -b;

while (b != 0) {

long long t = a % b;

a = b;

b = t;

return a;

int main() {

long long n1, d1, n2, d2;

printf("Enter numerator and denominator of first fraction


(separated by space): ");

if (scanf("%lld %lld", &n1, &d1) != 2) {

printf("Invalid input.\n");

return 1;

printf("Enter numerator and denominator of second fraction


(separated by space): ");

if (scanf("%lld %lld", &n2, &d2) != 2) {

printf("Invalid input.\n");

return 1;

}
// Validate denominators

if (d1 == 0 || d2 == 0) {

printf("Denominator cannot be zero.\n");

return 1;

// Compute LCM safely: lcm = (d1 / gcd(d1,d2)) * d2

long long g = gcd(d1, d2);

long long lcm = (d1 / g) * d2; // safe from overflow a bit


better than d1*d2

// Convert and add numerators

long long sum_num = n1 * (lcm / d1) + n2 * (lcm / d2);

long long sum_den = lcm;

// Simplify the fraction

long long g2 = gcd(sum_num, sum_den);

if (g2 != 0) { // avoid divide by zero (shouldn't happen)

sum_num /= g2;

sum_den /= g2;

// Ensure denominator positive

if (sum_den < 0) {

sum_den = -sum_den;
sum_num = -sum_num;

// Print result as improper fraction

printf("Sum = %lld/%lld\n", sum_num, sum_den);

// (Optional) Print as mixed number if absolute numerator >=


denominator

if (llabs(sum_num) >= sum_den) {

long long whole = sum_num / sum_den;

long long rem = llabs(sum_num % sum_den);

if (rem != 0)

printf("Mixed number = %lld %lld/%lld\n", whole, rem,


sum_den);

else

printf("Mixed number = %lld\n", whole);

return 0;

Explanation of the C Code (Line-by-line highlights)


●​ gcd() uses the Euclidean algorithm and works with negative values by taking
absolute values.​
●​ Input: read n1 d1 and n2 d2 separately (easy and predictable).​

●​ Validate denominators: stop if d1 or d2 is zero.​

●​ g = gcd(d1, d2) and lcm = (d1 / g) * d2 — LCM computed this way


reduces intermediate overflow risk.​

●​ Scale numerators to the common denominator (lcm) and add to get sum_num.​

●​ Simplify result with g2 = gcd(sum_num, sum_den) and divide numerator and


denominator by g2.​

●​ Make denominator positive (move sign to numerator).​

●​ Print the simplified improper fraction and optionally a mixed-number form.​

Python Program (Manual, clear)


def gcd(a, b):

a, b = abs(a), abs(b)

while b:

a, b = b, a % b

return a

# Input

n1 = int(input("Enter numerator of first fraction: "))

d1 = int(input("Enter denominator of first fraction: "))

n2 = int(input("Enter numerator of second fraction: "))

d2 = int(input("Enter denominator of second fraction: "))

# Validate
if d1 == 0 or d2 == 0:

print("Denominator cannot be zero.")

raise SystemExit(1)

# LCM

g = gcd(d1, d2)

lcm = (d1 // g) * d2

# Add

sum_num = n1 * (lcm // d1) + n2 * (lcm // d2)

sum_den = lcm

# Simplify

g2 = gcd(sum_num, sum_den)

if g2 != 0:

sum_num //= g2

sum_den //= g2

# Ensure positive denominator

if sum_den < 0:

sum_den = -sum_den

sum_num = -sum_num

print(f"Sum = {sum_num}/{sum_den}")
# Optional mixed number

if abs(sum_num) >= sum_den:

whole = sum_num // sum_den

rem = abs(sum_num % sum_den)

if rem != 0:

print(f"Mixed number = {whole} {rem}/{sum_den}")

else:

print(f"Mixed number = {whole}")

Python Short Version (Using fractions module)


from fractions import Fraction

n1 = int(input("Enter numerator of first fraction: "))

d1 = int(input("Enter denominator of first fraction: "))

n2 = int(input("Enter numerator of second fraction: "))

d2 = int(input("Enter denominator of second fraction: "))

if d1 == 0 or d2 == 0:

print("Denominator cannot be zero.")

else:

result = Fraction(n1, d1) + Fraction(n2, d2)


print("Sum =", result) # prints in lowest terms, e.g.
5/6

# mixed number

whole = [Link] // [Link]

rem = abs([Link] % [Link])

if rem:

print(f"Mixed number = {whole} {rem}/{[Link]}")

else:

print(f"Mixed number = {whole}")

More Examples
1.​ Input: 1/2 + 1/3 → Output: 5/6​

2.​ Input: 2/3 + 4/6 → 2/3 + 2/3 = 4/3 → Simplified: 4/3 → Mixed: 1 1/3​

3.​ Input: -1/4 + 1/2 → -1/4 + 2/4 = 1/4 → Output: 1/4​

4.​ Input: 3/4 + 5/4 → 8/4 = 2 → Mixed: 2 (or 2/1 as improper)​

42. Write a Program to Find the Largest


Element in an Array

Definition
An array is a collection of elements (numbers, characters, etc.) stored in contiguous memory
locations.​
Finding the largest element means identifying the element with the maximum value in that
array.

Logic (Concept in Simple Terms)


1.​ Read all the elements of the array from the user.​

2.​ Assume the first element is the largest initially.​

3.​ Compare each element in the array with the current largest element.​

4.​ If any element is greater than the current largest, update it.​

5.​ After scanning all elements, the variable holding the largest value is the answer.​

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input the number of elements in the array (say n).​

3.​ Declare an array of size n.​

4.​ Input n elements from the user.​

5.​ Initialize a variable max = arr[0].​

6.​ For each element arr[i] from index 1 to n-1:​

○​ If arr[i] > max, then max = arr[i].​

7.​ Print max as the largest element.​

8.​ End​

Dry Run Example


Input:

Array = [10, 25, 3, 78, 56]

Process:

Ste Current Element Current Max Compariso Updated Max


p n

1 10 10 Start 10

2 25 10 25 > 10 25

3 3 25 3 < 25 25

4 78 25 78 > 25 78

5 56 78 56 < 78 78

✅ Output: Largest Element = 78

C Program to Find the Largest Element in an Array


#include <stdio.h>

int main() {

int n, i;

float arr[100], max;


// Step 1: Input the number of elements

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

// Step 2: Input array elements

printf("Enter %d elements:\n", n);

for (i = 0; i < n; i++) {

scanf("%f", &arr[i]);

// Step 3: Initialize max with first element

max = arr[0];

// Step 4: Compare each element with max

for (i = 1; i < n; i++) {

if (arr[i] > max) {

max = arr[i]; // Update max if current element is


greater

// Step 5: Print the largest element

printf("The largest element in the array is: %.2f\n", max);

return 0;
}

Explanation of the C Code

Ste Description
p

1 The program takes input for the number of elements in the array.

2 It stores all the values entered by the user into the array arr[].

3 The variable max is initialized with the first element of the array.

4 The loop checks each element — if any element is greater than max, it updates
max.

5 After checking all elements, the program prints the value stored in max, which is the
largest number.

Example Input & Output


Input:

Enter the number of elements in the array: 5

Enter 5 elements:

10 25 3 78 56

Output:
The largest element in the array is: 78.00

Python Program to Find the Largest Element in an


Array
Method 1 — Using Loop

# Step 1: Take input for number of elements

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

# Step 2: Input elements into the list

arr = []

print("Enter the elements:")

for i in range(n):

element = float(input())

[Link](element)

# Step 3: Initialize max with the first element

max_value = arr[0]

# Step 4: Compare each element to find the maximum

for i in range(1, n):

if arr[i] > max_value:

max_value = arr[i]
# Step 5: Display the result

print("The largest element in the array is:", max_value)

Method 2 — Using Built-in Function

Python provides a direct and simple method using the max() function.

arr = list(map(float, input("Enter the array elements separated by


space: ").split()))

print("The largest element in the array is:", max(arr))

Detailed Conceptual Explanation


1.​ Initialization:​
We assume the first element is the largest (max = arr[0]).​

2.​ Comparison:​
Loop through the rest of the elements one by one.​
If any element is larger than the current max, update max with that value.​

3.​ Final Output:​


After all elements are checked, max holds the largest value in the array.​

4.​ Edge Case Handling:​

○​ If there’s only one element, that element is automatically the largest.​

○​ The logic works for integers, floats, and even negative numbers.​

○​ For example, in [-5, -10, -3, -20], the largest element is -3.​

Dry Run (Example 2)


Input:​
Array = [-5, -10, -3, -20]

Process:

Ste Element Current Max Compariso Updated Max


p n

1 -5 -5 Start -5

2 -10 -5 -10 < -5 -5

3 -3 -5 -3 > -5 -3

4 -20 -3 -20 < -3 -3

✅ Output:​
The largest element in the array is: -3

Summary of Algorithm

Ste Action Purpose


p

1 Take input of array size and elements Store user data

2 Initialize max = arr[0] Assume first element as largest

3 Compare each element with current Update max when a larger value is
max found
4 Print max Display result

✅ Final Output Example


Enter the number of elements in the array: 6

Enter 6 elements:

45 12 67 34 89 23

The largest element in the array is: 89.00

44. Write a Program to Find the Roots of


a Quadratic Equation

Definition
A quadratic equation is a second-degree equation in the form:

ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0

where

●​ a, b, and c are real numbers,​

●​ and a ≠ 0 (since if a = 0, it becomes a linear equation).​

The roots (solutions) of this equation are the values of x that satisfy the equation.

Mathematical Formula
The roots of a quadratic equation are found using the quadratic formula:
x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}x=2a−b±b2−4ac​​

Here,

●​ b2−4acb^2 - 4acb2−4ac is called the discriminant (D).​

●​ The nature of the roots depends on the discriminant.​

Nature of Roots Based on Discriminant

Discriminant (D) Nature of Roots Explanation

D>0 Real and Distinct Two different real roots

D=0 Real and Equal Both roots are the same

D<0 Complex / Imaginary No real roots, roots are complex


conjugates

Logic (Concept)
1.​ Input the coefficients a, b, and c.​

2.​ Compute the discriminant: D = b*b - 4*a*c.​

3.​ Depending on the value of D:​

○​ If D > 0 → two real and distinct roots.​

○​ If D = 0 → two equal real roots.​

○​ If D < 0 → two complex roots.​

4.​ Calculate roots accordingly using the quadratic formula.​


5.​ Display the result.​

Algorithm (Step-by-Step)
1.​ Start​

2.​ Input coefficients a, b, c.​

3.​ Check if a == 0 → if yes, print "Not a quadratic equation" and exit.​

4.​ Compute the discriminant: D = b*b - 4*a*c.​

5.​ If D > 0,​

Compute:​

root1 = (-b + sqrt(D)) / (2*a)

root2 = (-b - sqrt(D)) / (2*a)

○​
6.​ If D == 0,​

Compute:​

root1 = root2 = -b / (2*a)

○​
7.​ If D < 0,​

Compute real and imaginary parts:​



realPart = -b / (2*a)

imagPart = sqrt(-D) / (2*a)

○​

Roots are:​

root1 = realPart + imagPart i
root2 = realPart - imagPart i

○​
8.​ Print the roots.​

9.​ End.​

C Program to Find the Roots of a Quadratic Equation


#include <stdio.h>

#include <math.h>

int main() {

double a, b, c, discriminant, root1, root2, realPart, imagPart;

// Step 1: Input coefficients

printf("Enter coefficients a, b, and c: ");

scanf("%lf %lf %lf", &a, &b, &c);

// Step 2: Validate quadratic equation

if (a == 0) {

printf("Not a quadratic equation (a cannot be 0).\n");

return 0;

// Step 3: Calculate discriminant

discriminant = b * b - 4 * a * c;
// Step 4: Determine nature of roots

if (discriminant > 0) {

// Two distinct real roots

root1 = (-b + sqrt(discriminant)) / (2 * a);

root2 = (-b - sqrt(discriminant)) / (2 * a);

printf("Roots are real and distinct.\n");

printf("Root1 = %.2lf and Root2 = %.2lf\n", root1, root2);

else if (discriminant == 0) {

// Two equal real roots

root1 = root2 = -b / (2 * a);

printf("Roots are real and equal.\n");

printf("Root1 = Root2 = %.2lf\n", root1);

else {

// Complex roots

realPart = -b / (2 * a);

imagPart = sqrt(-discriminant) / (2 * a);

printf("Roots are complex and imaginary.\n");

printf("Root1 = %.2lf + %.2lfi and Root2 = %.2lf -


%.2lfi\n", realPart, imagPart, realPart, imagPart);

return 0;
}

Explanation of C Code

Ste Description
p

1 User inputs the coefficients a, b, and c.

2 The program checks that a is not zero (since it must be quadratic).

3 Discriminant is calculated as b*b - 4*a*c.

4 If D > 0 → real and distinct roots are calculated using the quadratic formula.

5 If D = 0 → both roots are equal (-b / 2a).

6 If D < 0 → complex roots are calculated with real and imaginary parts.

7 The result is displayed based on the discriminant.

Example 1: Real and Distinct Roots


Input:

Enter coefficients a, b, and c: 1 -3 2


Process:

D = (-3)^2 - 4*1*2 = 9 - 8 = 1

Roots:

x = (3 ± √1) / 2

=> Root1 = 2, Root2 = 1

Output:

Roots are real and distinct.

Root1 = 2.00 and Root2 = 1.00

Example 2: Real and Equal Roots


Input:

Enter coefficients a, b, and c: 1 -2 1

Process:

D = (-2)^2 - 4*1*1 = 4 - 4 = 0

Roots:

x = 2 / 2 = 1

Output:

Roots are real and equal.

Root1 = Root2 = 1.00


Example 3: Complex Roots
Input:

Enter coefficients a, b, and c: 1 2 5

Process:

D = 2^2 - 4*1*5 = 4 - 20 = -16

Roots:

x = (-2 ± √(-16)) / 2

x = (-2 ± 4i) / 2

x = -1 ± 2i

Output:

Roots are complex and imaginary.

Root1 = -1.00 + 2.00i and Root2 = -1.00 - 2.00i

Python Program to Find the Roots of a Quadratic


Equation
Method 1 — Using Conditional Logic

import math
# Step 1: Input coefficients

a = float(input("Enter coefficient a: "))

b = float(input("Enter coefficient b: "))

c = float(input("Enter coefficient c: "))

# Step 2: Validate

if a == 0:

print("Not a quadratic equation.")

else:

# Step 3: Calculate discriminant

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

# Step 4: Find nature of roots

if D > 0:

root1 = (-b + [Link](D)) / (2*a)

root2 = (-b - [Link](D)) / (2*a)

print("Roots are real and distinct.")

print("Root1 =", root1, "and Root2 =", root2)

elif D == 0:

root1 = root2 = -b / (2*a)

print("Roots are real and equal.")

print("Root1 = Root2 =", root1)

else:

realPart = -b / (2*a)
imagPart = [Link](-D) / (2*a)

print("Roots are complex and imaginary.")

print(f"Root1 = {realPart} + {imagPart}i and Root2 =


{realPart} - {imagPart}i")

Method 2 — Using cmath Module (Handles Complex Roots


Automatically)

import cmath # complex math module

a = float(input("Enter coefficient a: "))

b = float(input("Enter coefficient b: "))

c = float(input("Enter coefficient c: "))

if a == 0:

print("Not a quadratic equation.")

else:

D = [Link](b**2 - 4*a*c)

root1 = (-b + D) / (2*a)

root2 = (-b - D) / (2*a)

print("The roots are:")

print("Root1 =", root1)

print("Root2 =", root2)


Conceptual Summary

Concept Description

Quadratic Equation ax² + bx + c = 0

Discriminant (D) b² - 4ac

D>0 Real and distinct roots

D=0 Real and equal roots

D<0 Complex conjugate


roots

Quadratic Formula (-b ± √D) / (2a)

Algorithm Summary

Ste Action Purpose


p

1 Take coefficients a, b, c Get equation input

2 Compute discriminant D Check nature of roots

3 Apply formula based on D Find exact roots


4 Print results Show calculated
roots

✅ Final Output Example


Enter coefficients a, b, and c: 1 2 1

Roots are real and equal.

Root1 = Root2 = -1.00

You might also like