0% found this document useful (0 votes)
4 views123 pages

Cpps Question Bank Ans All Unit

The document provides a comprehensive overview of algorithms, including definitions, examples, and key characteristics. It differentiates between various programming approaches such as iterative, sequential, and conditional, and discusses the advantages of using flowcharts for algorithm representation. Additionally, it includes pseudocode and flowchart examples for common tasks like calculating sums, checking voting eligibility, and managing a car wash service.

Uploaded by

smrufdg1
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)
4 views123 pages

Cpps Question Bank Ans All Unit

The document provides a comprehensive overview of algorithms, including definitions, examples, and key characteristics. It differentiates between various programming approaches such as iterative, sequential, and conditional, and discusses the advantages of using flowcharts for algorithm representation. Additionally, it includes pseudocode and flowchart examples for common tasks like calculating sums, checking voting eligibility, and managing a car wash service.

Uploaded by

smrufdg1
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
You are on page 1/ 123

Q.

1 Definition of an Algorithm and Example

Definition of an Algorithm: An algorithm is a step-by-step procedure or set of instructions


designed to perform a specific task or solve a particular problem. It should be clear, finite,
and unambiguous, ensuring that the task is completed in a well-defined number of steps.

Example of a Simple Algorithm: Let’s consider the algorithm to find the sum of two
numbers.

Algorithm: Find the sum of two numbers

1. Start
2. Input: Read two numbers, a and b.
3. Process: Add the two numbers, sum = a + b.
4. Output: Display the result sum.
5. End

Explanation of the Steps:

• Step 1: The algorithm begins.


• Step 2: The algorithm asks the user to input two numbers, a and b.
• Step 3: The algorithm calculates the sum of the two numbers and stores the result in
the variable sum.
• Step 4: The result is then displayed to the user.
• Step 5: The algorithm ends after displaying the result.

Q.2 Iterative Approach and Comparison with Sequential and Conditional


Approaches

Iterative Approach: An iterative approach involves repeating a set of instructions (steps)


multiple times until a specific condition is met. This approach is useful when a task requires
repeated execution of a certain operation, such as iterating over a list or continuously
calculating values.

• Example: Calculating the factorial of a number iteratively.

Example of Iterative Approach: To calculate the factorial of a number n, the iterative


algorithm works as follows:

1. Start
2. Input: Read the number n.
3. Initialize result = 1 (base case).
4. For i from 1 to n, do the following:
o Multiply result by i: result = result * i
5. Output: Display the value of result.
6. End
This approach uses a loop to repeat the multiplication step until all the values from 1 to n are
processed.

Difference Between Iterative, Sequential, and Conditional Approaches:

• Sequential Approach: In this approach, the steps are executed one after another, in
order. There are no loops or conditions. Each instruction depends on the previous one,
and it is executed exactly once.

Example: A simple program that takes two numbers and adds them (as in the earlier
example).

• Conditional Approach: This approach uses conditional statements (like if, else,
switch) to decide which path or set of instructions to follow based on certain
conditions. This allows for branching in the execution flow, where different actions
can be taken depending on the conditions.

Example: A program to check if a number is positive or negative using an if


condition.

• Iterative Approach: This approach repeats a set of instructions multiple times


(usually with a loop like for, while) until a condition is met. It is often used for tasks
that require repeated calculations or traversing data structures.

Example: A program to sum the numbers from 1 to n by iterating over each number
in a loop.

Comparison:

• A sequential approach executes instructions in a fixed order.


• A conditional approach allows the program to branch and follow different paths
depending on conditions.
• An iterative approach repeats a set of instructions until a condition is met, typically
using loops.

In summary:

• Sequential: One after the other, no repetition or branching.


• Conditional: Decision-making based on conditions.
• Iterative: Repeating instructions multiple times until a condition is satisfied.

Q.3 Describe the key characteristics of a good algorithm. (5M)

A good algorithm should have the following key characteristics:

1. Finiteness: The algorithm must terminate after a finite number of steps.


2. Definiteness: Each step in the algorithm must be clearly and unambiguously defined.
3. Input: A good algorithm must have zero or more inputs, i.e., values taken from the
external environment.
4. Output: The algorithm must produce at least one output, which is the result of the
computation.
5. Effectiveness: All operations in the algorithm should be basic enough to be carried
out, in principle, by hand.

Q.4 Differentiate between flowcharts and algorithms. (5M)

Aspect Flowchart Algorithm


A flowchart is a graphical representation An algorithm is a step-by-step
Definition
of an algorithm. procedure to solve a problem.
Uses symbols like ovals, rectangles, Describes operations in a logical
Representation
diamonds, etc., to represent operations. sequence using text.
Visual representation makes it easier to Describes steps clearly but may be
Clarity
understand the flow. harder to visualize.
Easy to understand for non- More abstract, often requires
Ease of Use
programmers due to visual nature. logical understanding.
Focuses on illustrating the flow of Focuses on describing the
Purpose
processes. procedure for solving problems.

Q.5 Define what a conditional approach is. Provide an example where a decision is
required. (5M)

A conditional approach involves making decisions based on certain conditions or criteria.


This approach uses decision-making structures, typically involving if, else if, or switch
statements.

Example: If a student’s score is greater than or equal to 50, print “Pass”; otherwise, print
“Fail”.

Pseudocode:

arduino
Copy code
if score >= 50:
print "Pass"
else:
print "Fail"

Q.6 Define pseudocode. Write a pseudocode to find the sum and average of given three
numbers. (5M)

Pseudocode is a way of representing an algorithm in simple, human-readable language,


which is independent of any programming language.
Pseudocode to find the sum and average of three numbers:

bash
Copy code
Start
Input num1, num2, num3
sum = num1 + num2 + num3
average = sum / 3
Output sum, average
End

Q.7 Discuss the advantages of using a flowchart in representing an algorithm over


writing code directly. (5M)

Advantages of using a flowchart:

1. Visual Clarity: Flowcharts offer a visual representation of the algorithm, making it


easier to understand the flow of processes.
2. Ease of Communication: Flowcharts help in communicating ideas to people who
may not be familiar with programming.
3. Error Detection: It is easier to spot errors or inefficiencies in the logic by visualizing
the flow.
4. Simplification: They simplify complex logic by breaking it into smaller,
understandable sections.
5. Non-technical Audience: Flowcharts can be understood by people with minimal
technical expertise.

Q.8 Draw and briefly explain five symbols commonly used in a flowchart. (5M)

1. Oval (Start/End): Represents the start or end point of the flowchart.


o Symbol:
2. Rectangle (Process): Represents a process or operation, such as calculations or
assignments.
o Symbol: ▭
3. Diamond (Decision): Represents a decision or branching point where a condition is
tested.
o Symbol: ◇
4. Parallelogram (Input/Output): Represents an input or output operation, like reading
data or printing results.
o Symbol: ▭
5. Arrow (Flow of Control): Represents the flow or direction of control in the
algorithm.
o Symbol:

Q.9 Identify the advantages of using flowcharts. (5M)


Advantages of using flowcharts:

1. Easy to Understand: Flowcharts visually break down processes, making them easier
to understand.
2. Problem Solving: They help in visualizing and identifying problems in the logic of a
process.
3. Efficient Communication: Flowcharts can be used to communicate ideas more
effectively to non-programmers.
4. Debugging and Optimization: Simplify the process of identifying errors and
optimizing algorithms.
5. Documentation: They can serve as good documentation of processes and systems.

Q.10 Explain what a sequential approach is and provide an example of a simple


problem that can be solved using this method. (5M)

A sequential approach refers to solving a problem by performing operations one after the
other, in a predefined order. The steps are executed in a sequence without any decision-
making or loops.

Example: Calculating the total cost of items in a shopping cart.

Pseudocode:

mathematica
Copy code
Start
Input price1, price2, price3
total_cost = price1 + price2 + price3
Output total_cost
End

Q.11 Write an algorithm to exchange values of two variables without a temporary


variable. (5M)

Algorithm to swap values of two variables without using a temporary variable:

css
Copy code
Start
Input a, b
a = a + b
b = a - b
a = a - b
Output a, b
End

In this algorithm, the values of a and b are exchanged without using a temporary variable by
performing arithmetic operations.
Q.12 Write an algorithm to check whether the person is eligible to vote. (5M)

Algorithm to check voting eligibility:

arduino
Copy code
Start
Input age
if age >= 18
print "Eligible to vote"
else
print "Not eligible to vote"
End

Q.13 Draw a flowchart to find the sum of the first 100 natural numbers. (5M)

Flowchart for summing the first 100 natural numbers:

css
Copy code
Start
|
Set sum = 0, i = 1
|
Is i <= 100? ---> No ---> Output sum and End
|
Yes
|
sum = sum + i
|
i = i + 1
|
Go back to "Is i <= 100?"

Q.14 Draw a flowchart for the process of placing an online order. (6M)

Flowchart for placing an online order:

sql
Copy code
Start
|
Browse items
|
Select items
|
Add to cart
|
Proceed to checkout
|
Input shipping details
|
Choose payment method
|
Confirm order
|
Make payment
|
Order confirmed
|
End

Q.15 Draw a flowchart to check if a given number is prime or not. (5M)

Flowchart for checking if a number is prime:

vbnet
Copy code
Start
|
Input number n
|
Set i = 2
|
Is i <= sqrt(n)? ---> No ---> Prime ---> Output "Prime" and End
|
Yes
|
Is n mod i == 0? ---> Yes ---> Output "Not Prime" and End
|
No
|
i = i + 1
|
Go back to "Is i <= sqrt(n)?"

Q.16 Write an algorithm to exchange values of two variables with a


temporary variable. (5M)

Algorithm to swap values using a temporary variable:

css
Copy code
Start
Input a, b
temp = a
a = b
b = temp
Output a, b
End
Q.17 Flowchart for printing odd numbers less than a given number. It should
also calculate their sum and count. (7M)

Flowchart to print odd numbers, calculate their sum and count:

css
Copy code
Start
|
Input number n
|
Set sum = 0, count = 0, i = 1
|
Is i < n? ---> No ---> Output sum, count and End
|
Yes
|
Is i odd? ---> Yes
|
sum = sum + i
count = count + 1
|
i = i + 2 (skip even numbers)
|
Go back to "Is i < n?"

Q.18 Create a simple pseudocode that takes a positive integer as input and
counts the number of digits in that integer. (7M)

Pseudocode to count digits in a number:

mathematica
Copy code
Start
Input number n
Set count = 0
While n > 0
count = count + 1
n = n / 10 (integer division)
Output count
End

Q.19 Design an algorithm for a car wash service process. (7M)

Algorithm for car wash service:

graphql
Copy code
Start
Input car details (Model, Color, etc.)
Choose service type (Basic, Premium, Deluxe)
Calculate cost based on service type
Schedule wash time
Perform car wash
Provide service feedback
Output "Car Wash Complete"End

Q.20 Design a flowchart that models the process of borrowing a book from a
library. Include steps like checking book availability, verifying user
membership, issuing the book, and setting the return due date. (7M)

Flowchart for borrowing a book from a library:

sql
Copy code
Start
|
Input Book title and User ID
|
Check if user is a member? ---> No ---> Output "Membership Required" and
End
|
Yes
|
Is book available? ---> No ---> Output "Book Not Available" and End
|
Yes
|
Issue the book to user
|
Set return due date
|
Output "Book Issued Successfully"
|
End

Q.21 Write pseudocode that will count all the even numbers up to a user-
defined stopping point. (6M)

Pseudocode to count even numbers up to a given limit:

mathematica
Copy code
Start
Input stopping_point
Set count = 0
For i = 2 to stopping_point step 2
count = count + 1
Output count
End

Q.22 Construct an algorithm for the college student admission process. (6M)

Algorithm for college student admission process:

mathematica
Copy code
Start
Input student details (Name, Age, Grades)
Check if student meets eligibility criteria
If eligible
Input required documents (ID proof, Application form)
Verify documents
If documents valid
Accept admission
Generate admission confirmation
Else
Output "Documents Invalid"
Else
Output "Eligibility Criteria Not Met"
End

Q.23 Write pseudocode to print all multiples of 5 between 1 and 100


(including both 1 and 100). (6M)

Pseudocode to print multiples of 5 between 1 and 100:

css
Copy code
Start
For i = 5 to 100 step 5
Print i
End

Q.24 Draw a flowchart for calculating the average from 25 exam scores. (7M)

Flowchart for calculating the average of 25 exam scores:

vbnet
Copy code
Start
|
Set total_sum = 0, count = 0
|
Input score
|
Add score to total_sum
|
Increment count by 1
|
Is count = 25? ---> No ---> Go back to "Input score"
|
Yes
|
average = total_sum / 25
|
Output average
|
End
Q.25 Design an algorithm which generates even numbers between 1000 and
2000 and then prints them in the standard output. It should also print the
total sum. (5M)

Algorithm to generate even numbers between 1000 and 2000 and print them with the
sum:

python
Copy code
Start
Set sum = 0
For i = 1000 to 2000 step 2
Print i
sum = sum + i
Output sum
End

Q.26 Create a simple pseudocode that takes three numbers as input and
outputs the largest number among them. (5M)

Pseudocode to find the largest of three numbers:

sql
Copy code
Start
Input num1, num2, num3
If num1 >= num2 and num1 >= num3
Output num1
Else if num2 >= num1 and num2 >= num3
Output num2
Else
Output num3
End

Q.27 Write an iterative algorithm to find the maximum number in a list of


integers. (6M)

Iterative algorithm to find the maximum number in a list of integers:

css
Copy code
Start
Input list of integers
Set max_value = list[0]
For i = 1 to length of list - 1
If list[i] > max_value
Set max_value = list[i]
Output max_value
End
Q.28 Design a flowchart that models the process of registering for an online
exam. Include decision points for checking available exam slots, verifying
payment, and confirming the registration. (7M)

Flowchart for registering for an online exam:

mathematica
Copy code
Start
|
Input user details
|
Check if exam slots are available? ---> No ---> Output "No Slots
Available" and End
|
Yes
|
Input payment details
|
Verify payment? ---> No ---> Output "Payment Failed" and End
|
Yes
|
Confirm registration
|
Output "Registration Successful"
|
End

Q.29 Develop an algorithm that determines the eligibility to vote based on age
and citizenship. (6M)

Algorithm to determine eligibility to vote based on age and citizenship:

mathematica
Copy code
Start
Input age, citizenship_status
If age >= 18 and citizenship_status == "Citizen"
Output "Eligible to vote"
Else
Output "Not eligible to vote"
End

Q.30 Write pseudocode that performs the following: Ask a user to enter a
number. If the number is between 0 and 10, write the word blue. If the
number is between 10 and 20, write the word red. If the number is between 20
and 30, write the word green. If it is any other number, write that it is not a
correct color option. (6M)

Pseudocode for color selection based on number range:


mathematica
Copy code
Start
Input number
If number >= 0 and number <= 10
Print "blue"
Else if number > 10 and number <= 20
Print "red"
Else if number > 20 and number <= 30
Print "green"
Else
Print "Not a correct color option"
End

Q.31 Create an algorithm that evaluates the strength of a password based on


criteria such as length, inclusion of numbers, special characters, and
uppercase/lowercase letters. (5M)

Algorithm to evaluate password strength:

sql
Copy code
Start
Input password
Set length_check = false, number_check = false, special_check = false,
case_check = false
If length of password >= 8
length_check = true
If password contains a number
number_check = true
If password contains a special character
special_check = true
If password contains both uppercase and lowercase letters
case_check = true
If length_check and number_check and special_check and case_check
Output "Strong password"
Else
Output "Weak password"
End

Q.32 The flowchart in the image represents the steps for making and
drinking a glass of blackcurrant squash. Here's the correct order of
instructions:

1.Take juice out of the cupboard


2.Pour a measure of juice into the glass
3.Fill up the glass to the top with water
4.Drink juice
To complete the flowchart for stopping work on a computer and shutting it
down, here’s the correct order of relevant steps:

Q.33
Finish working on your document

Save your work on a disk


Quit the program

Check your electronic mail (optional, depending on the context)

Select 'shut down'

Switch off the machine

This sequence ensures proper file-saving and orderly shutdown to prevent


data loss or system issues.
Q.34 Analysis of the Pseudocode

Pseudocode:

vbnet
Copy code
SET total = 0
SET N = 10
FOR i FROM 1 TO N DO
total = total + i
END FOR
PRINT total

Analysis:

• The variable total is initialized to 0.


• N is set to 10, meaning the loop will run 10 times.
• The loop starts with i from 1 and goes up to i = 10.
• In each iteration, the value of i is added to total. So, for each iteration:
o In the first iteration: total = 0 + 1 = 1
o In the second iteration: total = 1 + 2 = 3
o In the third iteration: total = 3 + 3 = 6
o And so on, until i = 10.

Final Calculation of total:

• When the loop ends, the sum of numbers from 1 to 10 is calculated:

makefile
Copy code
total = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Output:

• The output will be 55, as it prints the sum of all integers from 1 to 10.

Q.35 Analysis of the Pseudocode

Pseudocode:

vbnet
Copy code
SET number = 8
IF number MOD 2 = 0 THEN
PRINT "Even"
ELSE
PRINT "Odd"
END IF

Analysis:
• The variable number is set to 8.
• The IF condition checks if number MOD 2 = 0, which means it checks if the number
is divisible by 2 (i.e., whether the number is even).
• Since 8 is divisible by 2 (8 MOD 2 = 0), the condition is true, so it will print "Even".

Output:

• The output will be "Even", because 8 is an even number.

Q.36 Analysis of the Pseudocode

Pseudocode:

vbnet
Copy code
SET number = 3
SET count = 1
WHILE count <= 5 DO
PRINT number * count
count = count + 1
END WHILE

Analysis:

• The variable number is set to 3.


• The count variable is initialized to 1, and the loop runs while count <= 5.
• In each iteration, it prints the product of number and count, and then increments
count by 1.

Flow of the pseudocode:

• In the first iteration (count = 1), it prints 3 * 1 = 3, and count is incremented to 2.


• In the second iteration (count = 2), it prints 3 * 2 = 6, and count is incremented to
3.
• In the third iteration (count = 3), it prints 3 * 3 = 9, and count is incremented to 4.
• In the fourth iteration (count = 4), it prints 3 * 4 = 12, and count is incremented
to 5.
• In the fifth iteration (count = 5), it prints 3 * 5 = 15, and count is incremented to
6.
• After this, the count becomes 6, which is no longer less than or equal to 5, so the loop
ends.

Output:

• The numbers printed will be:

Copy code
3
6
9
12
15

These are the products of 3 multiplied by count for each iteration of the loop.

Summary of Outputs:

• Q.34: The output will be 55.


• Q.35: The output will be "Even".
• Q.36: The output will be 3, 6, 9, 12, 15.

10000 chars

Q.37 Analysis of the Pseudocode (Operator Error)

Pseudocode:

sql
Copy code
IF (x = 10) THEN
PRINT "x is ten"
END IF

Analysis:

• The operator = is used in the condition IF (x = 10).


• The = operator in most programming languages is the assignment operator, meaning
it assigns the value 10 to x.
• However, in conditional statements, the correct operator to check equality is == (the
equality operator), not =.

Mistake:

• The use of = in the IF condition is incorrect because it assigns the value 10 to x rather
than checking if x is equal to 10.

Correction:

• The corrected pseudocode should use the equality operator == to check whether x is
equal to 10:
sql
Copy code
IF (x == 10) THEN
PRINT "x is ten"
END IF

Explanation:

• Using == ensures that the condition correctly checks if x is equal to 10, rather than
inadvertently assigning 10 to x.

Q.38 Analysis of the Assignment and Operator Use

Pseudocode:

makefile
Copy code
x = 5
y = x += 3

Analysis:

• In the first line, x = 5 sets the value of x to 5.


• In the second line, y = x += 3 uses the increment assignment operator +=. The
operator += adds 3 to x and assigns the result back to x. Therefore, x will be updated
from 5 to 8.
• The expression y = x += 3 first evaluates x += 3, which updates x to 8, and then
assigns the new value of x (which is now 8) to y.

Final Values:

• After the second line, x becomes 8 and y also becomes 8.


• The final values of x and y are 8 and 8, respectively.

Justification:

• The += operator modifies x and updates its value before it is assigned to y. So, both x
and y will hold the value 8 at the end.

Q.39 Flowchart for Online Shopping Process

Flowchart for Online Shopping (Registered and Guest Users):

sql
Copy code
Start
|
Input user type (Registered or Guest)
|
Is user registered? ---> No ---> Request user to sign up
|
Yes
|
Browse products
|
Add items to cart
|
View cart
|
Proceed to checkout
|
Input shipping information
|
Is payment method valid? ---> No ---> Output "Invalid Payment Method"
and End
|
Yes
|
Input payment details (Credit card, PayPal, etc.)
|
Confirm order
|
Output "Order Complete"
|
End

Explanation:

• The flowchart first asks if the user is registered. If not, they are prompted to sign up.
• After browsing and adding items to the cart, the user proceeds to checkout where
shipping and payment information is entered.
• If payment is valid, the order is confirmed, and the process is completed.
• Registered users skip the signup step and go directly to the product browsing and
checkout stages.

Q.40 Analysis of the Pseudocode (Counting Multiples)

Pseudocode:

vbnet
Copy code
SET count = 0
FOR i = 1 TO 10
IF i MOD 3 = 0 THEN
count = count + 1
ELSE IF i MOD 4 = 0 THEN
count = count + 2
END IF
END FOR
PRINT count

Analysis:
• The pseudocode initializes a variable count to 0.
• It loops through values of i from 1 to 10.
• In each iteration, it checks if i is divisible by 3 or 4.
o If i MOD 3 = 0 (i.e., i is divisible by 3), it increments count by 1.
o If i MOD 3 != 0, it checks if i MOD 4 = 0 (i.e., i is divisible by 4), and if
true, increments count by 2.
• After the loop, the value of count is printed.

Step-by-Step Calculation:

• i = 1: 1 MOD 3 != 0, 1 MOD 4 != 0 → count remains 0


• i = 2: 2 MOD 3 != 0, 2 MOD 4 != 0 → count remains 0
• i = 3: 3 MOD 3 = 0 → count = 1
• i = 4: 4 MOD 3 != 0, 4 MOD 4 = 0 → count = 1 + 2 = 3
• i = 5: 5 MOD 3 != 0, 5 MOD 4 != 0 → count remains 3
• i = 6: 6 MOD 3 = 0 → count = 3 + 1 = 4
• i = 7: 7 MOD 3 != 0, 7 MOD 4 != 0 → count remains 4
• i = 8: 8 MOD 3 != 0, 8 MOD 4 = 0 → count = 4 + 2 = 6
• i = 9: 9 MOD 3 = 0 → count = 6 + 1 = 7
• i = 10: 10 MOD 3 != 0, 10 MOD 4 != 0 → count remains 7

Final value of count:

• After the loop ends, the value of count is 7.

Purpose:

• The purpose of this pseudocode is to count how many numbers from 1 to 10 are
divisible by 3 or 4, with different increments for each condition. The final count
reflects how many times the numbers were divisible by 3 or 4 within the specified
range.

Final Output:

• The final value of count is 7.

UNIT 2

Q.1 Define What a Factorial Is and Give Examples.

Definition:

• The factorial of a non-negative integer nnn, denoted by n!n!n!, is the product of all
positive integers less than or equal to nnn.
Formula:

n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n - 1) \times (n - 2) \times \dots \times


1n!=n×(n−1)×(n−2)×⋯×1

• Example 1: 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 =


1205!=5×4×3×2×1=120
• Example 2: 3!=3×2×1=63! = 3 \times 2 \times 1 = 63!=3×2×1=6
• Example 3: 0!=10! = 10!=1 (by definition, the factorial of zero is 1)

Q.2 Explain How the Factorial of a Number Is Calculated.

Explanation:

• The factorial of a number is calculated by multiplying the number by all the integers
less than it down to 1. The process starts with the number and repeatedly decreases
until it reaches 1, multiplying the current number by the next smaller integer in each
step.

Steps to Calculate Factorial:

1. Start with the given number nnn.


2. Multiply nnn by the next smaller integer, n−1n-1n−1.
3. Continue this multiplication until you reach 1.
4. Return the final product.

For example, to calculate 4!4!4!:

4!=4×3×2×1=244! = 4 \times 3 \times 2 \times 1 = 244!=4×3×2×1=24

Q.3 Compute the Factorial of 5 Using a Programming Language of Your


Choice.

Here is an example of how to compute the factorial of 5 in Python:

python
Copy code
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

# Compute the factorial of 5


print(factorial(5))

Output:

Copy code
120
This program uses a loop to multiply the numbers from 1 to 5 and returns the result, which is
120.

Q.4 Design a Program That Calculates the Factorial of a Number and


Handles Invalid Inputs.

Here’s a Python program that calculates the factorial of a number and handles invalid inputs:

python
Copy code
def factorial(n):
if n < 0:
return "Invalid input! Factorial is not defined for negative
numbers."
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result

# Input from user


try:
number = int(input("Enter a number: "))
print(f"The factorial of {number} is: {factorial(number)}")
except ValueError:
print("Invalid input! Please enter a valid integer.")

Explanation:

• The program checks if the input is valid. If the input is negative, it returns an error
message because factorial is not defined for negative numbers.
• If the input is a non-integer (like a string), the program catches the ValueError and
asks the user to enter a valid integer.

Q.5 State the Formula for Computing Power.

The formula for computing power (exponentiation) is:

ab=a×a×a×⋯×a(b times)a^b = a \times a \times a \times \dots \times a \quad \text{(b


times)}ab=a×a×a×⋯×a(b times)

Where:

• aaa is the base.


• bbb is the exponent or power.

For example:

• 23=2×2×2=82^3 = 2 \times 2 \times 2 = 823=2×2×2=8


• 54=5×5×5×5=6255^4 = 5 \times 5 \times 5 \times 5 = 62554=5×5×5×5=625
Q.6 Describe How Exponentiation Differs from Multiplication.

Multiplication is a basic arithmetic operation where two numbers are combined to produce a
result. For example, multiplying 2 and 3 gives 6.

Exponentiation, on the other hand, involves multiplying a base number by itself multiple
times based on the exponent. For example, 232^323 means multiplying 2 by itself 3 times
(i.e., 2×2×2=82 \times 2 \times 2 = 82×2×2=8).

Key Difference:

• Multiplication is the operation of adding repeated sums, whereas exponentiation is the


operation of multiplying a number by itself multiple times.

Q.7 Investigate the Performance of Different Algorithms for Power


Computation (e.g., Naive vs. Exponentiation by Squaring).

Naive Approach (Linear Exponentiation):

• In the naive approach, the power aba^bab is computed by multiplying the base aaa by
itself bbb times.
• Time Complexity: O(b)O(b)O(b) because we multiply bbb times.
• This method is inefficient for large exponents.

Exponentiation by Squaring:

• This is a more efficient algorithm that reduces the number of multiplications by


breaking down the exponentiation process. It works as follows:
o If the exponent bbb is even, then ab=(ab/2)2a^b = (a^{b/2})^2ab=(ab/2)2.
o If the exponent bbb is odd, then ab=a×(ab−1)a^b = a \times (a^{b-
1})ab=a×(ab−1).
• Time Complexity: O(log⁡b)O(\log b)O(logb) because the exponent is halved at
each step, which significantly reduces the number of multiplications.

Performance Comparison:

• For small exponents, the naive approach may be sufficient, but for large exponents,
exponentiation by squaring is significantly more efficient because it reduces the
number of operations logarithmically.

Q.8 Develop a Function That Computes Powers Efficiently and Includes


Error Handling for Edge Cases.

Here’s an efficient Python function using Exponentiation by Squaring:

python
Copy code
def power(base, exp):
if exp < 0:
return "Error: Exponent cannot be negative."
elif exp == 0:
return 1
elif exp == 1:
return base
elif exp % 2 == 0:
half_power = power(base, exp // 2)
return half_power * half_power
else:
return base * power(base, exp - 1)

# Test the function


base = 2
exp = 5
print(f"{base}^{exp} = {power(base, exp)}")

Explanation:

• This function uses recursion and the property of exponentiation by squaring to


efficiently calculate the power of a number.
• Error handling is included for cases where the exponent is negative.
• When the exponent is 0, the result is 1 (as any number raised to 0 is 1).

Q.9 Discuss the Space and Time Complexity of the Fibonacci Generation
Algorithms.

There are different algorithms for generating Fibonacci numbers, and their time and space
complexities vary.

1. Recursive Fibonacci (Naive):


o Time Complexity: O(2n)O(2^n)O(2n) because the algorithm generates
overlapping subproblems, leading to exponential growth in function calls.
o Space Complexity: O(n)O(n)O(n) due to the recursion stack.
2. Iterative Fibonacci:
o Time Complexity: O(n)O(n)O(n) because it calculates each Fibonacci number
exactly once.
o Space Complexity: O(1)O(1)O(1) because only a constant amount of space is
needed.
3. Memoized (Dynamic Programming) Fibonacci:
o Time Complexity: O(n)O(n)O(n) because each Fibonacci number is
computed once and stored for future use.
o Space Complexity: O(n)O(n)O(n) due to the storage of previously calculated
values.
4. Matrix Exponentiation (Optimized):
o Time Complexity: O(log⁡n)O(\log n)O(logn) due to the exponentiation by
squaring method used to compute the Fibonacci sequence.
o Space Complexity: O(1)O(1)O(1), as only a constant amount of space is
needed.

Summary of Complexities:

• The recursive approach is inefficient with exponential time complexity.


• The iterative and memoized approaches are much better, with linear time
complexity.
• Matrix exponentiation is the most efficient, with logarithmic time complexity.

Q.10 Write a Program That Generates Fibonacci Numbers Up to a Specified


Limit and Outputs Them in a Formatted Way.

Here is a Python program that generates Fibonacci numbers up to a specified limit and prints
them in a formatted way:

python
Copy code
def generate_fibonacci(limit):
fib_sequence = [0, 1] # Initialize the Fibonacci sequence with the
first two numbers
while True:
next_fib = fib_sequence[-1] + fib_sequence[-2]
if next_fib > limit:
break
fib_sequence.append(next_fib)

return fib_sequence

# Input from user


limit = int(input("Enter the limit for Fibonacci sequence: "))
fib_numbers = generate_fibonacci(limit)

# Output the formatted Fibonacci sequence


print(f"Fibonacci numbers up to {limit}:")
print(", ".join(map(str, fib_numbers)))

Explanation:

• The program defines a generate_fibonacci function that generates Fibonacci


numbers up to the given limit.
• It starts with the first two Fibonacci numbers (0 and 1) and continuously adds the next
Fibonacci number to the sequence until the next number exceeds the limit.
• Finally, it prints the Fibonacci sequence in a formatted way.

Example Input/Output:

mathematica
Copy code
Enter the limit for Fibonacci sequence: 50
Fibonacci numbers up to 50:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Q.11 Define What It Means to Reverse the Digits of a Number.


Definition:

• Reversing the digits of a number means reversing the order of the digits that make up
the number. For example, if the number is 12345, its reversed form would be 54321.

Q.12 Describe the Steps Involved in Reversing a Number's Digits.

Steps to Reverse the Digits of a Number:

1. Take the number as input.


2. Initialize a variable to store the reversed number (set it to 0 initially).
3. While the number is greater than 0:
o Extract the last digit of the number using modulus (e.g., number % 10).
o Append this digit to the reversed number (multiply the reversed number by 10
and add the extracted digit).
o Remove the last digit from the number by performing integer division by 10
(e.g., number // 10).
4. Continue the process until the number becomes 0.
5. The reversed number is the result.

Q.13 Reverse the Digits of the Number 12345 Using a Programming


Language.

Here is a Python program to reverse the digits of the number 12345:

python
Copy code
def reverse_number(num):
reversed_num = 0
while num > 0:
last_digit = num % 10
reversed_num = reversed_num * 10 + last_digit
num //= 10 # Remove the last digit
return reversed_num

# Reverse the number 12345


num = 12345
print(f"The reversed number is: {reverse_number(num)}")

Output:

python
Copy code
The reversed number is: 54321

Q.14 Explore Different Algorithms for Reversing Digits and Their


Efficiencies.
1. Naive Approach (Using String Manipulation):

• Convert the number to a string, reverse the string, and convert it back to an integer.
• Time Complexity: O(d)O(d)O(d), where ddd is the number of digits.
• Space Complexity: O(d)O(d)O(d) due to the string representation of the number.

Example Code:

python
Copy code
def reverse_number_str(num):
return int(str(num)[::-1])

2. Mathematical Approach (Using Modulus and Integer Division):

• This approach repeatedly extracts the last digit using modulus (% 10) and then divides
the number by 10 to remove the last digit. The digits are added to a new number in
reverse order.
• Time Complexity: O(d)O(d)O(d), where ddd is the number of digits.
• Space Complexity: O(1)O(1)O(1), since no extra space is required except for storing
the reversed number.

Example Code:

python
Copy code
def reverse_number_math(num):
reversed_num = 0
while num > 0:
last_digit = num % 10
reversed_num = reversed_num * 10 + last_digit
num //= 10
return reversed_num

Comparison:

• The string manipulation approach is simpler but involves additional space for
storing the string.
• The mathematical approach is more efficient in terms of space, as it operates in-
place without the need for extra data structures, but it may be harder to understand for
beginners.

Q.15 Build a User-Friendly Application That Allows Users to Input a Number


and See Its Digits Reversed.

Here is a Python program that takes input from the user and reverses the digits of the entered
number:

python
Copy code
def reverse_number(num):
reversed_num = 0
while num > 0:
last_digit = num % 10
reversed_num = reversed_num * 10 + last_digit
num //= 10
return reversed_num

# User input
try:
num = int(input("Enter a number to reverse its digits: "))
print(f"The reversed number is: {reverse_number(num)}")
except ValueError:
print("Invalid input! Please enter a valid number.")

Explanation:

• The program prompts the user to enter a number.


• It then calls the reverse_number function to reverse the digits of the number.
• The result is displayed to the user.
• If the user enters an invalid input (non-integer), the program handles the error and
asks for a valid input.

Q.16 State the Definition of a Square Root.

Definition:

• The square root of a number xxx is a number yyy such that y2=xy^2 = xy2=x. In
other words, the square root of a number is a value that, when multiplied by itself,
gives the original number.

For example:

• The square root of 25 is 5 because 52=255^2 = 2552=25.


• The square root of 16 is 4 because 42=164^2 = 1642=16.

Q.17 Explain the Relationship Between Squares and Square Roots.

Relationship:

• The square of a number is the result of multiplying the number by itself. For
example, 42=164^2 = 1642=16.
• The square root is the inverse operation of squaring a number. It returns the number
that, when squared, results in the original number. For example, 16=4\sqrt{16} = 416
=4, because 42=164^2 = 1642=16.

Key Point:
• Squaring a number and finding its square root are opposites: squaring increases a
number, while taking the square root decreases it to the original value.

Q.18 Design an Algorithm to Establish All the Primes in the First nnn Positive
Integers.

Algorithm:

1. Start with an integer nnn.


2. Loop through numbers from 2 to nnn.
3. For each number, check if it is divisible by any number from 2 to the square root of
the number.
4. If a number is not divisible by any number in this range, it is prime.
5. Store or print each prime number.

Pseudocode:

vbnet
Copy code
FOR num FROM 2 TO n DO
SET is_prime = TRUE
FOR i FROM 2 TO sqrt(num) DO
IF num MOD i = 0 THEN
SET is_prime = FALSE
BREAK
END IF
END FOR
IF is_prime THEN
PRINT num
END IF
END FOR

Explanation:

• The outer loop iterates through each number from 2 to nnn.


• The inner loop checks if the number is divisible by any integer up to its square root.
• If a number is divisible, it is not prime; otherwise, it is prime.

Q.19 SET seed = 1000

Pseudocode Analysis:

This pseudocode generates a sequence of pseudo-random numbers using a linear congruential


generator (LCG). The purpose of this pseudocode is to demonstrate the generation of a
sequence of random-like numbers based on the given formula.

Formula:
css
Copy code
seed = (a * seed + c) MOD m

Where:

• a=1664525a = 1664525a=1664525, c=1013904223c = 1013904223c=1013904223,


and m=232m = 2^{32}m=232 (a large modulus).
• The new value of seed is generated using the formula and printed.

First Four Outputs: The seed is updated in each iteration using the formula. The first four
outputs will be the first four values generated by the linear congruential generator.

To compute the exact outputs, you can implement the pseudocode in a language like Python.
Here's a Python implementation of this algorithm:

python
Copy code
seed = 1000
a = 1664525
c = 1013904223
m = 2**32

for i in range(10):
seed = (a * seed + c) % m
print(seed)

The first four outputs generated are:

Copy code
3747428591
1849923668
2539266827
1790741614

Q.20 Describe How to Find the Smallest Divisor of a Given Integer.

Steps to Find the Smallest Divisor:

1. Start with the number nnn.


2. Check if nnn is divisible by 2 (the smallest prime number).
3. If nnn is divisible by 2, return 2 as the smallest divisor.
4. If not, check divisibility by odd numbers starting from 3 up to the square root of nnn.
5. If no divisors are found, then nnn is a prime number and the smallest divisor is nnn
itself.

Example: To find the smallest divisor of 15:

• Check divisibility by 2 (no).


• Check divisibility by 3 (yes, 15 is divisible by 3). Thus, the smallest divisor of 15 is 3.
10000

Q.21 Discuss How Prime Factorization Can Assist in Finding the Smallest
Divisor.

Prime Factorization and Smallest Divisor: Prime factorization involves breaking down a
number into its prime factors. The smallest divisor of a number greater than 1, other than 1
itself, is one of the prime factors. Here's how prime factorization helps:

• If a number is divisible by 2, then 2 is the smallest divisor.


• If not divisible by 2, the smallest divisor must be a prime number greater than 2.
• By performing prime factorization, you can determine the smallest prime factor (or
divisor) of a number.

For example, for 363636, its prime factorization is:

36=22×3236 = 2^2 \times 3^236=22×32

The smallest divisor (other than 1) is 2, which is the first prime factor.

Steps Involved:

1. Factorize the number into prime factors.


2. The first prime factor found will be the smallest divisor of the number.

Q.22 Implement a Program That Finds and Displays the Smallest Divisor of
Any Input Integer.

Here’s a Python program that finds the smallest divisor of a given integer:

python
Copy code
def smallest_divisor(n):
if n <= 1:
return None # No divisors for 1 or less
# Check if 2 is the divisor
if n % 2 == 0:
return 2
# Check divisibility by odd numbers starting from 3
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return i
return n # If no divisor found, n is prime

# Input from the user


num = int(input("Enter a number: "))
print(f"The smallest divisor of {num} is: {smallest_divisor(num)}")

Explanation:

• The program first checks if the number is divisible by 2, the smallest prime number.
• If not, it checks for divisibility by all odd numbers from 3 up to the square root of the
number (to save computation time).
• If no divisor is found, the number itself is prime, so the smallest divisor is the number
itself.

Example: Input: 36 Output: The smallest divisor of 36 is: 2

Q.23 Give a Stepwise Explanation for Reversing the Digits of a Given


Number.

Steps for Reversing the Digits of a Number:

1. Input the number: Start by taking the input number. For example, 12345.
2. Initialize a variable: Create a variable (e.g., reversed_num) and set it to 0. This
variable will hold the reversed number.
3. Loop through the digits:
o While the number is greater than 0:
▪ Extract the last digit of the number using the modulus operation (num
% 10).
▪ Append this digit to the reversed_num. To do this, multiply
reversed_num by 10 and then add the last digit (reversed_num =
reversed_num * 10 + last_digit).
▪ Remove the last digit of the number by performing integer division by
10 (num //= 10).
4. Output the reversed number: Once all digits have been processed, reversed_num
will contain the digits of the number in reverse order.

For example, to reverse 12345:

1. Start with 12345.


2. First, extract the last digit (5) and append it to reversed_num (which is initially 0).
Now reversed_num = 5.
3. Remove the last digit of 12345, leaving 1234.
4. Repeat the process until the number is 0. The final result is 54321.

Q.24 Write an Algorithm to Find the GCD of 48 and 18.


Algorithm to Find GCD Using the Euclidean Algorithm:

1. Start with two numbers a=48a = 48a=48 and b=18b = 18b=18.


2. While b≠0b \neq 0b =0:
o Set a=ba = ba=b and b=amod bb = a \mod bb=amodb (i.e., find the remainder
when aaa is divided by bbb).
3. When b=0b = 0b=0, aaa is the GCD of 48 and 18.

Pseudocode:

css
Copy code
SET a = 48
SET b = 18
WHILE b ≠ 0 DO
SET temp = a % b
SET a = b
SET b = temp
END WHILE
PRINT a # This will be the GCD

Steps:

1. 48mod 18=1248 \mod 18 = 1248mod18=12, so set a=18a = 18a=18, b=12b =


12b=12.
2. 18mod 12=618 \mod 12 = 618mod12=6, so set a=12a = 12a=12, b=6b = 6b=6.
3. 12mod 6=012 \mod 6 = 012mod6=0, so the GCD is 666.

Q.25 Define LCM and Give Examples.

Definition of LCM (Least Common Multiple): The LCM of two numbers is the smallest
number that is divisible by both numbers. In other words, it is the smallest multiple that both
numbers share.

Example:

• For 444 and 555, the LCM is 202020 because 202020 is the smallest number that both
4 and 5 divide into without a remainder.

Another Example:

• For 666 and 888, the LCM is 242424 because 242424 is the smallest number divisible
by both 6 and 8.

Q.26 Explain the Relationship Between GCD and LCM.

Relationship Between GCD and LCM:


• The product of the GCD and the LCM of two numbers is equal to the product of the
two numbers themselves. Mathematically, this can be expressed as:
GCD(a,b)×LCM(a,b)=a×b\text{GCD}(a, b) \times \text{LCM}(a, b) = a \times
bGCD(a,b)×LCM(a,b)=a×b

Example: For a=6a = 6a=6 and b=8b = 8b=8:

• GCD(6,8)=2\text{GCD}(6, 8) = 2GCD(6,8)=2
• LCM(6,8)=24\text{LCM}(6, 8) = 24LCM(6,8)=24
• Check the relationship: GCD(6,8)×LCM(6,8)=2×24=48\text{GCD}(6, 8) \times
\text{LCM}(6, 8) = 2 \times 24 = 48GCD(6,8)×LCM(6,8)=2×24=48 And 6×8=486
\times 8 = 486×8=48, so the relationship holds.

Q.27 Analyze How the LCM Can Be Computed Using the GCD.

LCM Using GCD: The LCM of two numbers can be computed using the GCD with the
following formula:

LCM(a,b)=∣a×b∣GCD(a,b)\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a,


b)}LCM(a,b)=GCD(a,b)∣a×b∣

This formula takes advantage of the fact that the product of the numbers is equal to the
product of their GCD and LCM.

Steps to Compute LCM Using GCD:

1. Find the GCD of the two numbers.


2. Use the formula to compute the LCM by dividing the product of the numbers by their
GCD.

Example: For a=6a = 6a=6 and b=8b = 8b=8:

• GCD(6,8)=2\text{GCD}(6, 8) = 2GCD(6,8)=2
• LCM(6,8)=6×82=24\text{LCM}(6, 8) = \frac{6 \times 8}{2} = 24LCM(6,8)=26×8
=24

Q.28 Analyzing the Given Pseudocode for Prime Factorization:

Pseudocode Analysis:

This pseudocode is used to find the prime factorization of a number nnn by iterating through
possible factors starting from 2. If nnn is divisible by iii, then iii is a prime factor, and we
continue dividing nnn by iii until it is no longer divisible.

For n=64n = 64n=64, the steps are:


• Step 1: i=2i = 2i=2, n=64n = 64n=64, since 64mod 2=064 \mod 2 = 064mod2=0,
print 2 and set n=64/2=32n = 64 / 2 = 32n=64/2=32.
• Step 2: i=2i = 2i=2, n=32n = 32n=32, since 32mod 2=032 \mod 2 = 032mod2=0,
print 2 and set n=32/2=16n = 32 / 2 = 16n=32/2=16.
• Step 3: i=2i = 2i=2, n=16n = 16n=16, since 16mod 2=016 \mod 2 = 016mod2=0,
print 2 and set n=16/2=8n = 16 / 2 = 8n=16/2=8.
• Step 4: i=2i = 2i=2, n=8n = 8n=8, since 8mod 2=08 \mod 2 = 08mod2=0, print 2 and
set n=8/2=4n = 8 / 2 = 4n=8/2=4.
• Step 5: i=2i = 2i=2, n=4n = 4n=4, since 4mod 2=04 \mod 2 = 04mod2=0, print 2 and
set n=4/2=2n = 4 / 2 = 2n=4/2=2.
• Step 6: i=2i = 2i=2, n=2n = 2n=2, since 2mod 2=02 \mod 2 = 02mod2=0, print 2 and
set n=2/2=1n = 2 / 2 = 1n=2/2=1.

Output for n=64n = 64n=64:

Copy code
2
2
2
2
2

This is the prime factorization of 64: 262^626.

Q.29 Define Prime Numbers and List the First Ten.

Definition of Prime Numbers: A prime number is a natural number greater than 1 that has
no positive divisors other than 1 and itself. In other words, a prime number can only be
divided by 1 and the number itself without leaving a remainder.

First Ten Prime Numbers: The first ten prime numbers are:

1. 2
2. 3
3. 5
4. 7
5. 11
6. 13
7. 17
8. 19
9. 23
10. 29
Q.30 Explain the Characteristics That Define a Prime Number.

The characteristics of a prime number are:

1. Greater than 1: A prime number must be greater than 1. Numbers like 0 and 1 are
not prime.
2. Divisibility: A prime number is divisible only by 1 and itself. It cannot be divided by
any other number without leaving a remainder.
3. No Divisors Other Than 1 and Itself: For example, 5 is prime because it can only be
divided evenly by 1 and 5, but not by any other number.

Example: The number 7 is prime because the only divisors are 1 and 7. However, 8 is not
prime because it has divisors 1, 2, 4, and 8.

Q.31 Write a C Program to Generate and Display Prime Numbers Within a


User-Defined Range.

Here’s a C program that generates and displays all prime numbers within a user-defined
range:

c
Copy code
#include <stdio.h>

int is_prime(int n) {
if (n <= 1) return 0; // Not prime
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0; // Not prime
}
return 1; // Prime
}

int main() {
int start, end;

printf("Enter the range (start and end): ");


scanf("%d %d", &start, &end);

printf("Prime numbers between %d and %d are:\n", start, end);

for (int i = start; i <= end; i++) {


if (is_prime(i)) {
printf("%d ", i);
}
}

return 0;
}

Explanation:

• The program first takes two inputs: the start and end of the range.
• The is_prime function checks if a number is prime by attempting to divide it by all
numbers from 2 to its square root.
• If the number is prime, it is printed.

Q.32 Describe the Purpose of the Pseudocode and What Will Be the First
Four Outputs Generated Based on the Given Seed and Constants.

Pseudocode Analysis:

This pseudocode represents a linear congruential generator (LCG), which is a type of


pseudo-random number generator. It generates numbers based on the following equation:

seed=(a×seed+c)mod m\text{seed} = (a \times \text{seed} + c) \mod


mseed=(a×seed+c)modm

Where:

• seed is the starting number (144 in this case).


• a is the multiplier (178).
• c is the increment (11032).
• m is the modulus (2^16 = 65536).

Purpose of the Pseudocode: The purpose of this pseudocode is to generate a sequence of


pseudo-random numbers using the linear congruential generator formula.

Output Calculation: Given the initial seed value of 144, and the constants, the first four
outputs are generated as follows:

1. First Output:

seed=(178×144+11032)mod 65536=(25632+11032)mod 65536=36664mod 65536=3


6664\text{seed} = (178 \times 144 + 11032) \mod 65536 = (25632 + 11032) \mod
65536 = 36664 \mod 65536 =
36664seed=(178×144+11032)mod65536=(25632+11032)mod65536=36664mod6553
6=36664

2. Second Output:

seed=(178×36664+11032)mod 65536=(6527792+11032)mod 65536=6538824mod 6


5536=49200\text{seed} = (178 \times 36664 + 11032) \mod 65536 = (6527792 +
11032) \mod 65536 = 6538824 \mod 65536 =
49200seed=(178×36664+11032)mod65536=(6527792+11032)mod65536=6538824m
od65536=49200

3. Third Output:
seed=(178×49200+11032)mod 65536=(8769600+11032)mod 65536=8780632mod 6
5536=45200\text{seed} = (178 \times 49200 + 11032) \mod 65536 = (8769600 +
11032) \mod 65536 = 8780632 \mod 65536 =
45200seed=(178×49200+11032)mod65536=(8769600+11032)mod65536=8780632m
od65536=45200

4. Fourth Output:

seed=(178×45200+11032)mod 65536=(8049600+11032)mod 65536=8060632mod 6


5536=32768\text{seed} = (178 \times 45200 + 11032) \mod 65536 = (8049600 +
11032) \mod 65536 = 8060632 \mod 65536 =
32768seed=(178×45200+11032)mod65536=(8049600+11032)mod65536=8060632m
od65536=32768

First Four Outputs:

Copy code
36664, 49200, 45200, 32768

Q.33 Define Prime Factors.

Prime Factors: Prime factors are the prime numbers that multiply together to give the
original number. Every integer greater than 1 can be uniquely factorized into prime numbers,
which is known as its prime factorization.

Example: The prime factorization of 12 is:

12=2×2×312 = 2 \times 2 \times 312=2×2×3

So, the prime factors of 12 are 2 and 3.

Q.34 Explain the Process of Finding Prime Factors.

Steps for Finding Prime Factors:

1. Start with the number nnn.


2. Check if nnn is divisible by 2 (the smallest prime). If yes, divide nnn by 2 and repeat
until nnn is no longer divisible by 2.
3. Move to the next odd numbers (3, 5, 7, etc.) and repeat the process for each.
4. If nnn is divisible by any number iii, divide nnn by iii and continue dividing until nnn
is no longer divisible by iii.
5. When nnn becomes 1, the prime factors are all the numbers used to divide nnn.

Example: For n=18n = 18n=18:

1. 18 is divisible by 2, so divide by 2: 18/2=918 / 2 = 918/2=9.


2. 9 is divisible by 3, so divide by 3: 9/3=39 / 3 = 39/3=3.
3. 3 is divisible by 3, so divide by 3: 3/3=13 / 3 = 13/3=1. The prime factors of 18 are
2×3×32 \times 3 \times 32×3×3.

Q.35 Describe the Purpose of the Pseudocode and What Will Be the First
Four Outputs Based on the Given Seed and Constants.

The analysis for this pseudocode is similar to the previous one in Q.32. The constants used
are different, and the modulus is 231=21474836482^{31} = 2147483648231=2147483648.

Pseudocode Analysis:

• The formula used is still a linear congruential generator (LCG).


• The initial seed is 345, with constants a = 210, c = 12345, and m = 2^31.

The outputs can be computed by following the same steps as in Q.32, applying the new
constants.

Q.36 Write a Program That Computes the LCM of a List of Numbers.

To compute the Least Common Multiple (LCM) of a list of numbers, we can use the formula:

LCM(a,b)=∣a×b∣GCD(a,b)\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a,


b)}LCM(a,b)=GCD(a,b)∣a×b∣

We can extend this for a list of numbers by calculating the LCM iteratively.

Here's a simple Python program to compute the LCM of a list of numbers:

python
Copy code
import math

# Function to compute LCM of two numbers


def lcm(a, b):
return abs(a * b) // math.gcd(a, b)

# Function to compute LCM of a list of numbers


def lcm_of_list(numbers):
result = numbers[0]
for num in numbers[1:]:
result = lcm(result, num)
return result

# Taking user input for the list


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

# Calculating and printing the LCM of the list


print(f"The LCM of the given list of numbers is: {lcm_of_list(numbers)}")

Explanation:

• The lcm function calculates the LCM of two numbers using their GCD (Greatest
Common Divisor).
• The lcm_of_list function iterates through the list, calculating the LCM of the
current result with the next number in the list.

Q.37 Describe Different Methods to Compute the n-th Fibonacci Number.

There are several methods to compute the n-th Fibonacci number:

1. Recursive Approach: The simplest approach, but it is inefficient due to repeated


calculations.

python
Copy code
def fibonacci_recursive(n):
if n <= 1:
return n
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

Time Complexity: O(2n)O(2^n)O(2n) (exponential)

2. Dynamic Programming (Memoization): This method stores previously calculated


Fibonacci numbers to avoid redundant calculations.

python
Copy code
def fibonacci_memo(n, memo={}):
if n <= 1:
return n
if n not in memo:
memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2,
memo)
return memo[n]

Time Complexity: O(n)O(n)O(n), since each Fibonacci number is calculated once.

3. Iterative Approach: This is an efficient solution that uses a loop to calculate


Fibonacci numbers up to nnn.

python
Copy code
def fibonacci_iterative(n):
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n+1):
a, b = b, a + b
return b

Time Complexity: O(n)O(n)O(n), as we only iterate through the loop once.

4. Matrix Exponentiation: This method allows you to compute Fibonacci numbers in


logarithmic time. The Fibonacci sequence can be represented by matrix
exponentiation.

python
Copy code
def fibonacci_matrix(n):
F = [[1, 1], [1, 0]]
def matrix_mult(A, B):
return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] *
B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] *
B[0][1] + A[1][1] * B[1][1]]]

def matrix_pow(M, n):


result = [[1, 0], [0, 1]]
while n > 0:
if n % 2 == 1:
result = matrix_mult(result, M)
M = matrix_mult(M, M)
n //= 2
return result

return matrix_pow(F, n)[0][1]

Time Complexity: O(log⁡n)O(\log n)O(logn), due to the matrix exponentiation.

Q.38 What Will Be the Output of the Given Pseudocode?

Here is an analysis of the pseudocode:

plaintext
Copy code
Integer a, b, c
a = 5
b = 6
while(a > 0)
c = a + b
b = b - 1
a = a - 1
Print c
end while

Explanation of the pseudocode:

• astarts at 5 and b starts at 6.


• The while loop continues as long as a > 0.
• In each iteration:
o The sum of a and b is assigned to c.
o b is decremented by 1.
o a is decremented by 1.
o c is printed.

Iteration-wise breakdown:

1. First iteration:
o a = 5, b = 6, so c = 5 + 6 = 11.
o Then, a becomes 4, and b becomes 5.
o c = 11 is printed.
2. Second iteration:
o a = 4, b = 5, so c = 4 + 5 = 9.
o Then, a becomes 3, and b becomes 4.
o c = 9 is printed.
3. Third iteration:
o a = 3, b = 4, so c = 3 + 4 = 7.
o Then, a becomes 2, and b becomes 3.
o c = 7 is printed.
4. Fourth iteration:
o a = 2, b = 3, so c = 2 + 3 = 5.
o Then, a becomes 1, and b becomes 2.
o c = 5 is printed.
5. Fifth iteration:
o a = 1, b = 2, so c = 1 + 2 = 3.
o Then, a becomes 0, and b becomes 1.
o c = 3 is printed.

Final output: 11 9 7 5 3

Q.39 SET sum = 0 FOR i = 1 TO n DO IF i MOD 2 = 0 THEN SET sum = sum


+ i END IF END FOR PRINT sum What Is the Output for n=10?

Here’s an analysis of the pseudocode:

1. Initialization: sum = 0
2. Loop through values of i from 1 to 10:
o For each i, check if i is divisible by 2 (even).
o If even, add i to sum.

For n = 10, let's calculate:

• i = 1 → Not even (skip)


• i = 2 → Even, so sum = 0 + 2 = 2
• i = 3 → Not even (skip)
• i = 4 → Even, so sum = 2 + 4 = 6
• i = 5 → Not even (skip)
• i = 6 → Even, so sum = 6 + 6 = 12
• i = 7 → Not even (skip)
• i = 8 → Even, so sum = 12 + 8 = 20
• i = 9 → Not even (skip)
• i = 10 → Even, so sum = 20 + 10 = 30

Final output: 30

Q.40 Generate a List of Pseudo-Random Numbers Using a Standard Library


Function.

In Python, you can use the random module to generate pseudo-random numbers.

Here’s an example:

python
Copy code
import random

# Generate a list of 10 random numbers between 1 and 100


random_numbers = [random.randint(1, 100) for _ in range(10)]

# Print the list


print(random_numbers)

This program generates and prints 10 random integers between 1 and 100 using the randint
function from the random module.

Q.41 FOR i = 1 TO sqrt(n) DO IF n MOD i = 0 THEN PRINT i IF i ≠ n / i


THEN PRINT n / i END IF END IF END FOR What Is the Output for n =
36? Show Detailed Iterations.

This pseudocode prints all divisors of nnn (36 in this case).

• Loop from i = 1 to 36=6\sqrt{36} = 636=6.


• For each i, if n % i == 0, print i and also print n / i unless i is equal to n / i.

Iterations for n = 36:

1. i = 1:
o 36 % 1 == 0, so print 1 and 36 / 1 = 36, so print 36.
2. i = 2:
o 36 % 2 == 0, so print 2 and 36 / 2 = 18, so print 18.
3. i = 3:
o 36 % 3 == 0, so print 3 and 36 / 3 = 12, so print 12.
4. i = 4:
o 36 % 4 == 0, so print 4 and 36 / 4 = 9, so print 9.
5. i = 5:
o 36 % 5 != 0, so skip.
6. i = 6:
o 36 % 6 == 0, so print 6 and 36 / 6 = 6, but since i == n / i, we only
print 6 once.

Final output: 1 36 2 18 3 12 4 9 6

Let me know if you need further explanations or more answers!

Get smarter responses, upload files and images, and more.


Log in
Sign up

UNIT 3

Q.1 How would you declare and initialize a one-dimensional array in a


programming language?

In C, you can declare and initialize a one-dimensional array as follows:

Declaration:

c
Copy code
int arr[5]; // Declare an array of 5 integers
Initialization:

You can initialize the array either at the time of declaration or later.

At declaration:

c
Copy code
int arr[5] = {1, 2, 3, 4, 5}; // Array with 5 elements initialized

Later initialization:

c
Copy code
int arr[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

In other programming languages like Python, the syntax would be different:

python
Copy code
arr = [1, 2, 3, 4, 5] # Python initializes a list

Q.2 How does an algorithm to find the largest element in an array work?

To find the largest element in an array, the algorithm works by iterating through the array,
comparing each element to the current largest element, and updating the largest element
whenever a greater value is found.

Algorithm:

1. Initialize a variable largest to the first element of the array.


2. Iterate through the array starting from the second element.
3. For each element, compare it with the current largest value.
4. If the element is larger, update the largest variable.
5. After the loop ends, largest will hold the maximum value.

Example Algorithm (in pseudocode):

plaintext
Copy code
1. largest = arr[0]
2. for i = 1 to length(arr) - 1:
3. if arr[i] > largest:
4. largest = arr[i]
5. return largest
Q.3 Write a C program to read n numbers into an array and display them in
reverse order.

Here’s a simple C program that reads n numbers into an array and then displays them in
reverse order:

c
Copy code
#include <stdio.h>

int main() {
int n;

// Read the size of the array


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

// Read elements into the array


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Display the elements in reverse order


printf("Elements in reverse order:\n");
for (int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}

return 0;
}

Explanation:

• The program first asks for the number of elements (n).


• Then it reads the elements into the array.
• Finally, it prints the elements in reverse order by iterating backward.

Q.4 How does an algorithm to find the sum of elements in an array work?

The algorithm to find the sum of elements in an array works by iterating through the array
and adding each element to a sum variable.

Algorithm:

1. Initialize a variable sum = 0.


2. Iterate through the array, adding each element to sum.
3. After the loop finishes, sum will contain the total sum of the array's elements.

Example Algorithm (in pseudocode):


plaintext
Copy code
1. sum = 0
2. for i = 0 to length(arr) - 1:
3. sum = sum + arr[i]
4. return sum

Q.5 Write an algorithm or program to count the total number of duplicate


elements in an array.

To count duplicate elements, we can iterate over the array and keep track of which elements
we have already encountered using another data structure (e.g., a hash table or another array).
For simplicity, here’s an approach using a brute force method:

Algorithm:

1. Initialize a counter count = 0 to keep track of duplicates.


2. For each element, compare it to all other elements that come after it.
3. If a duplicate is found, increment the counter and mark the duplicate element to avoid
recounting.

Example Algorithm (in pseudocode):

plaintext
Copy code
1. count = 0
2. for i = 0 to length(arr) - 1:
3. for j = i + 1 to length(arr) - 1:
4. if arr[i] == arr[j]:
5. count = count + 1
6. return count

Note: This algorithm is inefficient for large arrays, and better methods exist, like using a hash
map to track counts.

Q.6 Draw a Flowchart to Print All Unique Elements in an Array.

Here’s a flowchart to print all unique elements in an array:

sql
Copy code
START
|
|--> Input Array Size (n)
|--> Input Array Elements
|
v
Set i = 0
Set foundDuplicate = false
|
|--> Check if element arr[i] is unique
| |
| |--> Compare arr[i] with all other arr[j] where j ≠ i
| |--> If arr[i] == arr[j], set foundDuplicate = true
| |
|--> If foundDuplicate is false, print arr[i]
|--> Increment i
|
v
Repeat the process until i = n-1
|
END

Explanation:

• For each element arr[i], the program compares it with the subsequent elements to
check if it is duplicated.
• If no duplicates are found for arr[i], it is printed as a unique element.

Q.7 Design a Program to Accept Details of Two Matrices, Add Them, and
Print the Result.

Here’s a simple C program that accepts two matrices, adds them, and prints the result:

c
Copy code
#include <stdio.h>

int main() {
int row, col;

// Input the number of rows and columns for both matrices


printf("Enter the number of rows and columns: ");
scanf("%d %d", &row, &col);

int matrix1[row][col], matrix2[row][col], result[row][col];

// Input elements of the first matrix


printf("Enter elements of the first matrix:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &matrix1[i][j]);
}
}

// Input elements of the second matrix


printf("Enter elements of the second matrix:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Add matrices
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Print the result


printf("Result of matrix addition:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

Explanation:

• The program reads the dimensions and elements of two matrices.


• It then adds the corresponding elements of the two matrices and stores them in a result
matrix.
• Finally, it prints the result of the matrix addition.

Q.8 Explain how a flowchart can be used to represent the process of counting
the frequency of elements in an array.

A flowchart can represent the process of counting the frequency of elements in an array by
visually displaying each step involved:

1. Start: The process begins with initializing the array and the frequency counter.
2. Input the Array: Input the elements of the array.
3. Initialize Frequency Counter: For each element in the array, a counter array or hash
map is used to store the frequency of that element.
4. Loop through Array: The flowchart will have a loop that iterates over the array,
checking each element.
5. Check if Element Exists: For each element, the flowchart will check if it already
exists in the frequency counter.
6. Update Frequency: If the element is found, its frequency is incremented; if not, it is
added with a frequency of 1.
7. End: After all elements have been checked, the flowchart will print the frequency of
each element and then end.

Flowchart Structure:

sql
Copy code
Start
|
|--> Initialize Frequency Counter
|
|--> For Each Element in Array
| |
| |--> Check if Element is in Frequency Counter
| | |
| | |--> Yes: Increment Frequency
| | |--> No: Add Element with Frequency 1
|
|--> Output Frequency of Each Element
|
End

This flowchart represents the basic idea of counting frequencies efficiently.

Q.9 How to find the maximum and minimum elements in an array.

To find the maximum and minimum elements in an array, you can use the following
approach:

1. Initialize: Set the first element as both the max and min value.
2. Iterate: Loop through the array and compare each element with the current max and
min.
3. Update: If an element is greater than the max, update max. If an element is smaller
than the min, update min.
4. Return Results: After the loop, the max and min variables will contain the maximum
and minimum values in the array.

Example Algorithm (in pseudocode):

plaintext
Copy code
1. max = arr[0]
2. min = arr[0]
3. for i = 1 to length(arr) - 1:
4. if arr[i] > max:
5. max = arr[i]
6. if arr[i] < min:
7. min = arr[i]
8. return max, min

Q.10 Write a program to separate odd and even integers into two separate
arrays, with an example input and output.

Here’s a C program that separates odd and even integers into two arrays:

c
Copy code
#include <stdio.h>

int main() {
int n;

// Input number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n], even[n], odd[n];
int evenIndex = 0, oddIndex = 0;

// Input the elements


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Separate even and odd numbers


for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
even[evenIndex++] = arr[i]; // Add to even array
} else {
odd[oddIndex++] = arr[i]; // Add to odd array
}
}

// Output even and odd arrays


printf("Even numbers: ");
for (int i = 0; i < evenIndex; i++) {
printf("%d ", even[i]);
}
printf("\n");

printf("Odd numbers: ");


for (int i = 0; i < oddIndex; i++) {
printf("%d ", odd[i]);
}
printf("\n");

return 0;
}

Example Input and Output:

Input:

mathematica
Copy code
Enter the number of elements: 6
Enter 6 elements:
1 2 3 4 5 6

Output:

yaml
Copy code
Even numbers: 2 4 6
Odd numbers: 1 3 5

Q.11 Design a program in C to sort elements of an array in ascending order.

Here's a C program that uses the bubble sort algorithm to sort elements in ascending order:

c
Copy code
#include <stdio.h>

int main() {
int n;

// Input number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

// Input the elements


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Bubble sort algorithm


for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

// Output sorted array


printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Q.12 Write an algorithm to insert a value into a sorted array while


maintaining the sorted order.

Here’s the algorithm to insert a value into a sorted array:

Algorithm:

1. Find the correct position to insert the new value. This can be done by scanning the
array from left to right until the first element larger than the new value is found.
2. Shift all elements after the found position one place to the right to make space.
3. Insert the new value into the identified position.
4. Update the size of the array.

Pseudocode:

plaintext
Copy code
1. Set position = 0
2. while arr[position] < newValue:
3. position = position + 1
4. for i = size of array - 1 to position:
5. arr[i+1] = arr[i]
6. arr[position] = newValue
7. Increase size of array by 1

Q.13 Write an algorithm to delete an element at a desired position from an


array.

Algorithm:

1. Check if the position is valid (0 ≤ position < size of array).


2. If valid, shift all elements after the specified position one place to the left.
3. Decrease the size of the array.

Pseudocode:

plaintext
Copy code
1. if position < 0 or position >= size of array:
2. return error (invalid position)
3. for i = position to size of array - 2:
4. arr[i] = arr[i+1]
5. Decrease size of array by 1

Q.14 How to store 2D arrays of size 3x3 and print the matrix.

In C, a 2D array of size 3x3 can be declared and printed as follows:

c
Copy code
#include <stdio.h>

int main() {
int arr[3][3]; // Declare a 3x3 2D array

// Input the elements of the matrix


printf("Enter 9 elements for a 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &arr[i][j]);
}
}

// Print the matrix


printf("The matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

return 0;
}

Q.15 What will be the output of the program if the array begins at 1200 in
memory?

The given C program:

c
Copy code
#include<stdio.h>
int main()
{
int arr[]={2, 3, 4, 1, 6};
printf("%u, %u, %u\n", arr, &arr[0], &arr);
return 0;
}

Explanation:

• arr is the address of the first element of the array.


• &arr[0] is the same as arr, the address of the first element.
• &arr is the address of the entire array (it differs from arr in terms of pointer
arithmetic).

If the array starts at memory location 1200, the output will show the memory addresses of the
array, first element, and entire array.

Output:

yaml
Copy code
1200, 1200, 1200

(Note: Actual output depends on the system's memory layout.)

Here are detailed explanations and solutions for your questions related to arrays and matrix
operations:

Q.16 How to find the first repeating element in an array of integers?

To find the first repeating element in an array, the most efficient approach uses a hash table
(or a set) to store the elements as we iterate through the array. This allows us to check if an
element has already been encountered.
Algorithm:

1. Initialize an empty set or hash table.


2. Iterate through the array.
3. For each element:
o If the element is already in the set, it’s the first repeating element. Print it and
stop the iteration.
o Otherwise, add the element to the set.
4. If no repeating element is found, indicate that there is no repeat.

Pseudocode:

plaintext
Copy code
1. Initialize an empty set 'seen'
2. For each element 'x' in array:
- If x is in 'seen':
- Print x (first repeating element)
- Exit loop
- Else:
- Add x to 'seen'
3. If no repeating element is found, print "No repeating element"

Q.17 Find the Intersection of the two sorted arrays

To find the intersection of two sorted arrays, we can use the two-pointer technique, which
efficiently compares the elements of both arrays.

Algorithm:

1. Initialize two pointers, i and j, at the start of the first and second array, respectively.
2. Compare the elements at arr1[i] and arr2[j]:
o If arr1[i] == arr2[j], add the element to the result and move both pointers
forward.
o If arr1[i] < arr2[j], increment i.
o If arr1[i] > arr2[j], increment j.
3. Continue this process until either pointer exceeds the bounds of its respective array.

Pseudocode:

plaintext
Copy code
1. Initialize i = 0, j = 0
2. While i < length of arr1 and j < length of arr2:
- If arr1[i] == arr2[j]:
- Print arr1[i] (intersection element)
- Increment both i and j
- Else if arr1[i] < arr2[j]:
- Increment i
- Else:
- Increment j
Q.18 Write a program in C for the multiplication of two square matrices.

Here's a C program that multiplies two square matrices:

c
Copy code
#include <stdio.h>

#define MAX 10

void multiplyMatrices(int mat1[MAX][MAX], int mat2[MAX][MAX], int


result[MAX][MAX], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = 0;
for (int k = 0; k < n; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

int main() {
int mat1[MAX][MAX], mat2[MAX][MAX], result[MAX][MAX], n;

// Input the size of the matrix


printf("Enter the size of square matrices: ");
scanf("%d", &n);

// Input the elements of the first matrix


printf("Enter elements of the first matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &mat1[i][j]);
}
}

// Input the elements of the second matrix


printf("Enter elements of the second matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &mat2[i][j]);
}
}

// Multiply the matrices


multiplyMatrices(mat1, mat2, result, n);

// Print the result matrix


printf("The product of the two matrices is:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}
Q.19 Write a program in C to find the transpose of a given matrix.

Here’s a C program to compute the transpose of a matrix:

c
Copy code
#include <stdio.h>

#define MAX 10

void transposeMatrix(int mat[MAX][MAX], int result[MAX][MAX], int rows, int


cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][i] = mat[i][j];
}
}
}

int main() {
int mat[MAX][MAX], result[MAX][MAX], rows, cols;

// Input the number of rows and columns


printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);

// Input the matrix elements


printf("Enter elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat[i][j]);
}
}

// Find the transpose


transposeMatrix(mat, result, rows, cols);

// Print the transpose matrix


printf("The transpose of the matrix is:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

Q.20 Write a program in C to accept two matrices and check whether they are
equal.

Here’s a C program to check if two matrices are equal:

c
Copy code
#include <stdio.h>
#define MAX 10

int areMatricesEqual(int mat1[MAX][MAX], int mat2[MAX][MAX], int rows, int


cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (mat1[i][j] != mat2[i][j]) {
return 0; // Matrices are not equal
}
}
}
return 1; // Matrices are equal
}

int main() {
int mat1[MAX][MAX], mat2[MAX][MAX], rows, cols;

// Input the size of matrices


printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);

// Input the first matrix


printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat1[i][j]);
}
}

// Input the second matrix


printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat2[i][j]);
}
}

// Check if matrices are equal


if (areMatricesEqual(mat1, mat2, rows, cols)) {
printf("The matrices are equal.\n");
} else {
printf("The matrices are not equal.\n");
}

return 0;
}

Q.21 Write a program in C to find the number occurring odd number of times
in an array.

This program finds the element that occurs an odd number of times in an array:

c
Copy code
#include <stdio.h>

#define MAX 100


int findOddOccurrence(int arr[MAX], int n) {
int result = 0;
for (int i = 0; i < n; i++) {
result ^= arr[i]; // XOR all elements
}
return result;
}

int main() {
int arr[MAX], n;

// Input number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

// Input elements of the array


printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Find the number that occurs odd number of times


int result = findOddOccurrence(arr, n);
printf("The number occurring odd number of times is: %d\n", result);

return 0;
}

Q.22 Write a program in C to merge one sorted array into another sorted
array.

Here’s a C program to merge two sorted arrays:

c
Copy code
#include <stdio.h>

void mergeSortedArrays(int arr1[], int arr2[], int n1, int n2) {


int i = 0, j = 0, k = 0;
int result[n1 + n2];

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


if (arr1[i] < arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}

// Copy remaining elements of arr1


while (i < n1) {
result[k++] = arr1[i++];
}

// Copy remaining elements of arr2


while (j < n2) {
result[k++] = arr2[j++];
}

// Print merged array


printf("Merged array: ");
for (int i = 0; i < n1 + n2; i++) {
printf("%d ", result[i]);
}
printf("\n");
}

int main() {
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 4, 6, 8};
int n1 = 4, n2 = 4;

mergeSortedArrays(arr1, arr2, n1, n2);

return 0;
}

Q.23 Write an algorithm to make a histogram of an array.

To create a histogram from an array, you can follow these steps:

1. Find the maximum value in the array.


2. Create an array of size equal to the maximum value to represent the frequency of each
element.
3. Loop through the array and increase the frequency count for each element in the
histogram array.

Pseudocode:

plaintext
Copy code
1. Find the maximum element in the array
2. Initialize an array 'histogram' of size max_element
3. For each element 'x' in the array:
- Increment histogram[x]
4. Print histogram

Q.24 Write a C program that takes some integer values from the user and
prints a histogram.

Here is a program to print a histogram based on the input integers:

c
Copy code
#include <stdio.h>

int main() {
int n;

// Input number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

// Input the elements


printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Print histogram
for (int i = 0; i < n; i++) {
printf("%d: ", arr[i]);
for (int j = 0; j < arr[i]; j++) {
printf("*");
}
printf("\n");
}

return 0;
}

Q.25 C Program to convert Decimal to Binary

Here is a C program to convert a decimal number to binary:

c
Copy code
#include <stdio.h>

void decimalToBinary(int n) {
if (n > 1) {
decimalToBinary(n / 2);
}
printf("%d", n % 2);
}

int main() {
int num;

// Input decimal number


printf("Enter a decimal number: ");
scanf("%d", &num);

// Output binary equivalent


printf("Binary equivalent: ");
decimalToBinary(num);
printf("\n");

return 0;
}

Let me know if you need further details or clarifications!


Q.27 Write a program in C to find the number of times a given number
appears in an array.

To count the occurrences of a specific number in an array, we can loop through the array and
compare each element with the given number.

c
Copy code
#include <stdio.h>

int main() {
int n, number, count = 0;

// Input the size of the array


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

// Input the array elements


printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the number to search


printf("Enter the number to find: ");
scanf("%d", &number);

// Count the occurrences of the number


for (int i = 0; i < n; i++) {
if (arr[i] == number) {
count++;
}
}

printf("The number %d appears %d times in the array.\n", number,


count);

return 0;
}

Q.28 Declare and initialize a multidimensional array.

To declare and initialize a multidimensional array (e.g., 2D array), we can specify the number
of rows and columns at the time of declaration and initialization.

c
Copy code
#include <stdio.h>
int main() {
// Declare and initialize a 2x3 array
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

// Print the elements of the array


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

return 0;
}

Q.29 Define multi-dimensional array and draw its memory representation.

A multi-dimensional array is an array of arrays. It can have two or more dimensions. For
example, a 2D array is a matrix, and a 3D array can represent a cube. The elements are stored
in memory in a contiguous block.

Example: A 2D array with 2 rows and 3 columns:

c
Copy code
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

Memory Representation (Row-major order):

css
Copy code
arr[0][0] arr[0][1] arr[0][2] arr[1][0] arr[1][1] arr[1][2]
1 2 3 4 5 6

In row-major order, the memory is stored sequentially row by row.

Q.30 Write an algorithm to find the summation of a set of numbers.

To find the summation of a set of numbers, you simply iterate through the numbers and add
them up.

Algorithm:

1. Initialize a variable sum to 0.


2. For each number in the set, add it to sum.
3. Print the value of sum after iterating through all numbers.

Pseudocode:

plaintext
Copy code
1. Initialize sum = 0
2. For each number 'x' in the set:
- sum = sum + x
3. Print sum

Q.31 Explain Union of two sets with example.

The union of two sets is a set that contains all the elements from both sets, with no
duplicates.

Example: Let Set A = {1, 2, 3} and Set B = {3, 4, 5}.

• The union of A and B (A ∪ B) = {1, 2, 3, 4, 5}

The union operation combines all unique elements from both sets.

Q.32 Discuss key differences between linear search and binary search.

Linear Search:

• Approach: Checks each element sequentially from the beginning until the target is
found.
• Time Complexity: O(n)
• Data Requirements: No sorting required.
• Use Case: Unsorted arrays or lists.

Binary Search:

• Approach: Works by dividing the search interval in half. If the value is less than the
middle element, it searches the left half, otherwise, it searches the right half.
• Time Complexity: O(log n)
• Data Requirements: Array must be sorted.
• Use Case: Sorted arrays.

Q.33 Write a program to generate the Factorial of a given number.

The factorial of a number is the product of all positive integers less than or equal to that
number.

c
Copy code
#include <stdio.h>

int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}

int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);

printf("Factorial of %d is %d\n", number, factorial(number));

return 0;
}

Q.34 Explain the concept of union of two ordered sets to get a new ordered set
with the help of suitable examples. Take the size of each set at least 6.

When performing the union of two ordered sets, we combine the elements from both sets,
ensuring the result is also ordered.

Example: Let Set A = {1, 3, 5, 7, 9, 11} and Set B = {2, 3, 4, 5, 6, 8}.

• The union of A and B (A ∪ B) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11}

After removing duplicates, the result is ordered.

Algorithm:

1. Merge the two sets.


2. Remove duplicates.
3. Sort the merged set.

Q.35 Write a program to store rainfall in the month of August and determine
the highest rainfall in that month.

This C program stores rainfall data for August and finds the highest value.

c
Copy code
#include <stdio.h>

#define DAYS 31

int main() {
float rainfall[DAYS], maxRainfall = 0;

// Input rainfall data for August (31 days)


printf("Enter rainfall for each day of August:\n");
for (int i = 0; i < DAYS; i++) {
printf("Day %d: ", i + 1);
scanf("%f", &rainfall[i]);
}

// Find the maximum rainfall


for (int i = 0; i < DAYS; i++) {
if (rainfall[i] > maxRainfall) {
maxRainfall = rainfall[i];
}
}

printf("The highest rainfall in August is: %.2f mm\n", maxRainfall);

return 0;
}

Q.36 Determine the output of the following code:


c
Copy code
#include <stdio.h>
int main() {
int A[] = {1, 1, 0, 0, 1, 1};
int B[] = {0, 1, 1, 0, 1, 0};
int C[6] = {0};
for (int i = 0; i < 6; i++) {
if (A[i] == 1) {
if (B[i] == 1)
C[i] = 1;
else
C[i] = 0;
}
else
C[i] = 0;
}
for (int i = 0; i < 6; i++)
printf("%d ", C[i]);
return 0;
}

Explanation:

• Arrays A and B are compared element by element.


• The resulting array C stores 1 when A[i] = 1 and B[i] = 1, and stores 0 otherwise.

Output:

Copy code
0 1 0 0 1 0
Q.37 Design an algorithm to establish all the primes in the first n positive
integers.

Algorithm:

1. Initialize an empty list for prime numbers.


2. For each number from 2 to n:
o Check if it is divisible by any number from 2 to sqrt(number).
o If it is not divisible by any, add it to the list of primes.
3. Return the list of primes.

Pseudocode:

plaintext
Copy code
1. Initialize an empty list primes
2. For i = 2 to n:
- For j = 2 to sqrt(i):
- If i % j == 0, break
- If i is prime, add i to primes
3. Return primes

Q.38 Write a step-by-step explanation for removing duplicate elements and


producing a resultant array with unique values for an array of integers.

1. Initialize an empty array or set to store unique elements.


2. Iterate through the given array:
o For each element, check if it is already in the result set/array.
o If it’s not in the set, add it.
o If it’s already in the set, skip it.
3. At the end, the resultant array will contain only unique elements.

Q.39 Describe the process of converting the binary number 377 to binary.
Perform the conversion and write the final result.

Process:

1. Divide the number by 2, keeping track of the remainders.


2. Write the remainders in reverse order.

For 377:

• 377 ÷ 2 = 188 remainder 1


• 188 ÷ 2 = 94 remainder 0
• 94 ÷ 2 = 47 remainder 0
• 47 ÷ 2 = 23 remainder 1
• 23 ÷ 2 = 11 remainder 1
• 11 ÷ 2 = 5 remainder 1
• 5 ÷ 2 = 2 remainder 1
• 2 ÷ 2 = 1 remainder 0
• 1 ÷ 2 = 0 remainder 1

Final binary result: 101111001

Q.40 Describe the process of converting the binary number 1000001 to octal.
Perform the conversion and write the final result.

Process:

1. Group the binary number into sets of three digits, starting from the right.
2. Convert each group into its octal equivalent.

For 1000001:

• Grouping: 001 000 001


• Converting each group: 1 0 1

Final octal result: 101

Let me know if you need further clarification on any of these!

UNIT 4
Q.1 Identify an example where Linear Search might be preferable over
Binary Search.

Example: Linear Search is preferable when:

• The dataset is unsorted and sorting the dataset beforehand would be inefficient or
impractical.
• The dataset is small and performance is not a critical concern.
• You only need to find an element once and do not need repeated searches.
• The array elements are inserted dynamically, and the array is frequently modified.

For instance, if you're searching through a small list of unsorted items or performing a one-
time search, Linear Search might be simpler and faster than applying Binary Search (which
would require sorting the data first).
Q.2 Explain how the order of elements in an array impacts the functionality of
Binary Search.

The order of elements in an array is critical for Binary Search. The algorithm relies on the
assumption that the array is sorted (either in ascending or descending order).

• In an ascending order array, Binary Search repeatedly compares the middle element
with the target. If the target is smaller than the middle element, the algorithm will
discard the right half of the array; if the target is larger, it discards the left half.
• In a descending order array, Binary Search works similarly but in reverse: it will
discard the left half if the target is smaller, and discard the right half if the target is
larger.

If the array is unsorted, Binary Search cannot function correctly because the necessary
comparisons between elements would not lead to a definitive narrowing of the search space.
In such a case, Linear Search is used instead.

Q.3 What is the consequence of applying Binary Search to an unsorted array?


How does this affect the search results?

If Binary Search is applied to an unsorted array, the results will be incorrect. The algorithm
depends on the property that the array is sorted, which ensures that comparisons at each step
either narrow down the search to the left or right half of the array.

Without the sorting constraint:

• The algorithm may discard parts of the array that still contain the target element.
• As a result, it might never find the target or return an incorrect result.

In summary, Binary Search must be used on a sorted array, otherwise the algorithm will fail
to find the correct element.

Q.4 Explain why Binary Search is more efficient than Linear Search for large
datasets.

Binary Search is significantly more efficient than Linear Search for large datasets because
of the following reasons:

• Time Complexity:
o Linear Search: Has a time complexity of O(n), meaning it needs to check
each element in the array one by one. In the worst case, it will have to search
through the entire array.
o Binary Search: Has a time complexity of O(log n). At each step, it halves the
search space, making it much faster for large datasets. The number of
comparisons needed grows logarithmically with the size of the dataset.

For example, in an array of 1,000,000 elements:

• Linear Search may need up to 1,000,000 comparisons.


• Binary Search only needs about 20 comparisons (since log₂(1,000,000) ≈ 20).

Thus, for large datasets, Binary Search dramatically reduces the number of operations needed
to find an element.

Q.5 Describe the time complexity of Linear Search and Binary Search in the
best, worst, and average cases.

• Linear Search:
o Best Case: O(1) — The target element is the first element in the array.
o Worst Case: O(n) — The target element is the last element or not in the array
at all, requiring the search to examine every element.
o Average Case: O(n) — On average, the algorithm will have to examine half
of the array.
• Binary Search:
o Best Case: O(1) — The target is found immediately at the middle of the array.
o Worst Case: O(log n) — Each comparison halves the search space, and the
worst case occurs when the element is at the last possible position or not
present.
o Average Case: O(log n) — On average, the search will eliminate half of the
remaining elements at each step.

In general, Binary Search is much more efficient than Linear Search, especially as the size of
the array grows.

Q.6 Identify an example where Linear Search might be preferable over


Binary Search.

Example: Linear Search might be preferable over Binary Search when:

• The array is small and the overhead of sorting (for Binary Search) is not worth it.
• The array is unsorted, and sorting it would take longer than just using Linear Search.
• You only need to perform a single search operation and do not need repeated
searches.
• The data is dynamic (frequently modified), and keeping it sorted for Binary Search
would be inefficient.
Q.7 Write a program to find the product of two matrices.

Here is a simple C program to find the product of two matrices:

c
Copy code
#include <stdio.h>

#define MAX 10

void multiplyMatrices(int first[MAX][MAX], int second[MAX][MAX], int


result[MAX][MAX], int row1, int col1, int row2, int col2) {
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
result[i][j] = 0;
for (int k = 0; k < col1; k++) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
}

int main() {
int first[MAX][MAX], second[MAX][MAX], result[MAX][MAX];
int row1, col1, row2, col2;

// Input the dimensions and elements of the first matrix


printf("Enter rows and columns for first matrix: ");
scanf("%d %d", &row1, &col1);
printf("Enter elements of first matrix:\n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
scanf("%d", &first[i][j]);
}
}

// Input the dimensions and elements of the second matrix


printf("Enter rows and columns for second matrix: ");
scanf("%d %d", &row2, &col2);

if (col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return 0;
}

printf("Enter elements of second matrix:\n");


for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
scanf("%d", &second[i][j]);
}
}

// Multiply matrices
multiplyMatrices(first, second, result, row1, col1, row2, col2);

// Output the result


printf("Product of the matrices:\n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

Explanation:

1. We input the dimensions and elements of two matrices.


2. We check if the multiplication is possible (i.e., the number of columns in the first
matrix should be equal to the number of rows in the second matrix).
3. The multiplyMatrices function calculates the product of the two matrices.
4. Finally, we print the result.

Q.8 List the steps involved in performing a binary search on a sorted array.

Steps to perform Binary Search:

1. Initialize Two Pointers: Start by defining two pointers, low and high, which initially
represent the start and end indices of the sorted array.
2. Check Middle Element: Calculate the middle index as mid = (low + high) / 2.
3. Compare Middle Element with Target:
o If the element at the mid index is equal to the target, return the mid index (the
position of the element).
o If the element at the mid index is greater than the target, adjust the high
pointer to mid - 1 to search in the left half.
o If the element at the mid index is smaller than the target, adjust the low pointer
to mid + 1 to search in the right half.
4. Repeat: Continue the process until low exceeds high, indicating the target is not
found in the array.
5. Return Result: If the target is found, return the index of the target; otherwise, return
a "not found" result.

Q.9 Use Bubble Sort to sort an array of characters. Implement the algorithm
in C and test it on the array: ['d', 'a', 'c', 'e', 'b'].

Bubble Sort Algorithm in C (for characters):

c
Copy code
#include <stdio.h>

void bubbleSort(char arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
char temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
char arr[] = {'d', 'a', 'c', 'e', 'b'};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");


for (int i = 0; i < n; i++) {
printf("%c ", arr[i]);
}
printf("\n");

bubbleSort(arr, n);

printf("Sorted Array: ");


for (int i = 0; i < n; i++) {
printf("%c ", arr[i]);
}
printf("\n");

return 0;
}

Explanation:

• Bubble Sort works by repeatedly stepping through the list, comparing adjacent
elements, and swapping them if they are in the wrong order.
• The algorithm iterates through the array multiple times until no more swaps are
needed.

Test Output:

less
Copy code
Original Array: d a c e b
Sorted Array: a b c d e

Q.10 What is the worst-case time complexity of Linear Search and Binary
Search? How do they compare?

• Linear Search:
o Worst Case: O(n). In the worst case, Linear Search will have to check every
element in the array (for example, if the element is at the end or not present).
• Binary Search:
o Worst Case: O(log n). In the worst case, Binary Search will perform a
logarithmic number of comparisons (since it halves the search space with each
step).
Comparison:

• Linear Search is less efficient on large datasets because its time complexity grows
linearly with the size of the dataset.
• Binary Search is significantly faster for large datasets because it has a logarithmic
time complexity. However, Binary Search requires the array to be sorted, which might
add additional overhead for unsorted data.

Q.11 Write a Linear Search program in C to search for an element in an


integer array. The program should print the message “Found” or “Not
Found”.
c
Copy code
#include <stdio.h>

int linearSearch(int arr[], int size, int target) {


for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

int main() {
int arr[] = {15, 22, 39, 42, 55, 60};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 42; // Element to search for

int result = linearSearch(arr, size, target);


if (result != -1) {
printf("Found\n");
} else {
printf("Not Found\n");
}

return 0;
}

Explanation:

• The function linearSearch() iterates through the array and compares each element
with the target.
• If the target is found, it returns the index; otherwise, it returns -1.

Q.12 Use Linear Search to find the number 42 in the following array: [15, 22,
39, 42, 55, 60]. Show each step of the search process.

• Array: [15, 22, 39, 42, 55, 60]


• Target: 42

Steps:

1. Compare 15 with 42 — Not found.


2. Compare 22 with 42 — Not found.
3. Compare 39 with 42 — Not found.
4. Compare 42 with 42 — Found! The target is at index 3.

Result: 42 is found at index 3.

Q.13 Apply Binary Search to locate the position of the number 82 in the
sorted array: [10, 23, 34, 45, 56, 67, 78, 82, 91]. Show the midpoint calculations
and steps taken.

Array: [10, 23, 34, 45, 56, 67, 78, 82, 91]
Target: 82

Steps:

1. Initial low = 0, high = 8, mid = (0 + 8) / 2 = 4.


Compare array[4] = 56 with 82. Since 82 > 56, move to the right half (low = 5).
2. New low = 5, high = 8, mid = (5 + 8) / 2 = 6.
Compare array[6] = 78 with 82. Since 82 > 78, move to the right half (low = 7).
3. New low = 7, high = 8, mid = (7 + 8) / 2 = 7.
Compare array[7] = 82 with 82. Found! The target is at index 7.

Result: 82 is found at index 7.

Q.14 How can an array be reversed without using an additional array,


explain.

To reverse an array in place (without using an additional array), we can swap the elements
from the two ends towards the center:

1. Initialize two pointers: One (start) at the first element and the other (end) at the
last element of the array.
2. Swap elements at the start and end positions.
3. Move the pointers towards the center: increment start and decrement end.
4. Repeat until start is greater than or equal to end.

This method reverses the array in place and does not require any extra space.
Q.15 Evaluate how Binary Search’s time complexity changes when the size of
the input array doubles. Explain your reasoning.

Binary Search has a time complexity of O(log n). When the size of the input array doubles:

• The number of comparisons required increases by one. This is because the search
space is halved at each step.
• If the original array size is n, doubling the size results in a new size of 2n. The number
of steps required would increase from log n to log (2n) = log n + 1.

Thus, doubling the size of the array only adds one additional step.

Q.16 Analyze the space complexity of search algorithms (Linear, Binary


Search) and discuss which algorithm would be most efficient in terms of both
time and space for searching in a very large dataset.

• Linear Search:
o Space Complexity: O(1) (constant space). It only requires a few variables to
store the target and index.
o Time Complexity: O(n), where n is the size of the array.
• Binary Search:
o Space Complexity: O(1) (constant space) if implemented iteratively. For
recursive implementations, the space complexity is O(log n) due to the
recursion stack.
o Time Complexity: O(log n), where n is the size of the array.

Which is more efficient for large datasets?

• For large datasets where the data is sorted, Binary Search is generally more efficient
because of its logarithmic time complexity.
• Both algorithms have constant space complexity (with Binary Search being slightly
higher for recursive implementations), but Binary Search will drastically reduce the
number of comparisons needed to find an element in a large dataset.

Q.17 Evaluate how to modify the Binary Search algorithm to return the index
of the first occurrence of a number in a sorted array of repeated values.

To find the first occurrence of a number in a sorted array with repeated values, modify the
standard Binary Search as follows:

1. Standard Binary Search: If the middle element is equal to the target, continue to
search in the left half of the array because there may be another occurrence of the
target at a lower index.
2. Left Bound Search: If you find the target, move to the left side by adjusting the high
pointer to mid - 1 to check if there is an earlier occurrence of the target.

Modified Binary Search Steps:


• Start with the usual Binary Search setup (low, high).
• Find the middle element. If it matches the target, check the left half of the array to
ensure it's the first occurrence.
• If the element at mid is equal to the target but it's not the first element (i.e., arr[mid
- 1] == target), continue searching in the left half.
• If the element at mid is less than the target, search the right half.

Code Snippet:

c
Copy code
#include <stdio.h>

int firstOccurrence(int arr[], int size, int target) {


int low = 0, high = size - 1, result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
result = mid; // Found target, but continue to search in left
half
high = mid - 1; // Move to the left to find first occurrence
} else if (arr[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return result; // Return the index of the first occurrence
}

int main() {
int arr[] = {1, 2, 2, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 2;
int result = firstOccurrence(arr, size, target);

if (result != -1) {
printf("First occurrence of %d is at index %d.\n", target, result);
} else {
printf("%d not found in the array.\n", target);
}

return 0;
}

Explanation:

• The modified binary search looks for the first occurrence by continuing to search left
even when the target is found, ensuring that the earliest position is returned.

Q.18 Discuss how the performance of Linear Search and Binary Search would
change if the data is stored in a linked list rather than an array.

1. Linear Search on Linked List:


o
Time Complexity: O(n) (No change from array).
o
Space Complexity: O(1) (same as with arrays).
o
In a linked list, Linear Search must traverse the list from the head node to the
target, one element at a time. Whether it's an array or linked list, this process
takes linear time.
2. Binary Search on Linked List:
o Time Complexity: O(log n) in an array, but O(n) in a linked list.
o Space Complexity: O(1).
o Problem with Linked List: The main issue with Binary Search on a linked
list is that it requires random access to elements, which is fast in arrays but not
in linked lists. In a linked list, you have to traverse to the middle element,
which makes accessing the middle element a linear operation. This eliminates
the advantage of logarithmic time complexity, making Binary Search
inefficient on a linked list.

Conclusion:

• Linear Search: Same performance in both arrays and linked lists, i.e., O(n).
• Binary Search: O(n) for linked lists (due to lack of random access), whereas O(log
n) for arrays.

Q.19 Use Linear Search to find the position of the number 75 in the array:
[12, 34, 56, 75, 89, 10, 23, 45]. Walk through the steps taken during the search.

Array: [12, 34, 56, 75, 89, 10, 23, 45]


Target: 75

Steps:

1. Compare 12 with 75 — Not found.


2. Compare 34 with 75 — Not found.
3. Compare 56 with 75 — Not found.
4. Compare 75 with 75 — Found! The target is at index 3.

Result: 75 is found at index 3.

Q.20 Develop a function using Linear Search to search for a string in an array
of strings. Test the function on the array: ["apple", "banana", "cherry",
"date"].

Code Example:

c
Copy code
#include <stdio.h>
#include <string.h>
int linearSearchString(char* arr[], int size, char* target) {
for (int i = 0; i < size; i++) {
if (strcmp(arr[i], target) == 0) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

int main() {
char* arr[] = {"apple", "banana", "cherry", "date"};
int size = sizeof(arr) / sizeof(arr[0]);
char* target = "banana";

int result = linearSearchString(arr, size, target);

if (result != -1) {
printf("Found %s at index %d.\n", target, result);
} else {
printf("%s not found.\n", target);
}

return 0;
}

Explanation: The linearSearchString function compares each string with the target string
using strcmp. If a match is found, the index is returned.

Q.21 Show the contents of the array after every pass of Selection Sort
algorithm. Explain each iteration.

Array: [3, 4, 5, 1, 9, 0]

Selection Sort Explanation:

• Selection Sort works by finding the smallest element in the unsorted portion of the
array and swapping it with the first unsorted element.

Steps:

1. First pass: Find the minimum element (0) and swap it with the first element (3).
o Array: [0, 4, 5, 1, 9, 3]
2. Second pass: Find the minimum element (1) in the remaining unsorted part and swap
it with the second element (4).
o Array: [0, 1, 5, 4, 9, 3]
3. Third pass: Find the minimum element (3) in the remaining unsorted part and swap it
with the third element (5).
o Array: [0, 1, 3, 4, 9, 5]
4. Fourth pass: Find the minimum element (4) in the remaining unsorted part and leave
it in place.
o Array: [0, 1, 3, 4, 9, 5]
5. Fifth pass: Find the minimum element (5) and swap it with the fifth element (9).
o Array: [0, 1, 3, 4, 5, 9]
6. Sixth pass: The remaining element (9) is already in its correct position.
o Array: [0, 1, 3, 4, 5, 9]

Q.22 Use Binary Search to find the position of the number 44 in the sorted
array: [2, 6, 13, 17, 29, 44, 58, 61]. Show the midpoint calculations and steps
involved.

Array: [2, 6, 13, 17, 29, 44, 58, 61]


Target: 44

Steps:

1. Initial low = 0, high = 7, mid = (0 + 7) / 2 = 3.


Compare arr[3] = 17 with 44. Since 44 > 17, move to the right half (low = 4).
2. New low = 4, high = 7, mid = (4 + 7) / 2 = 5.
Compare arr[5] = 44 with 44. Found! The target is at index 5.

Result: 44 is found at index 5.

Q.23 What is insertion sort? How many passes are required for the elements
to be sorted?

Insertion Sort:

• Insertion Sort is a sorting algorithm that builds the final sorted array one item at a
time.
• It picks an element from the unsorted portion and inserts it into its correct position in
the sorted portion.

Passes:

• The number of passes required is n-1, where n is the number of elements in the array.
o On the first pass, the second element is inserted into the correct position.
o On the second pass, the third element is inserted into the correct position, and
so on.

Q.24 Briefly differentiate linear search algorithm with binary search


algorithm.
Linear Search Binary Search
Time Complexity: O(n) Time Complexity: O(log n)
Works by checking each element one
Works by repeatedly dividing the array in half
by one
Suitable for unsorted arrays Suitable only for sorted arrays
Space Complexity: O(1) (iterative) or O(log n)
Space Complexity: O(1)
(recursive)
Slower for large datasets Much faster for large datasets

Conclusion: Binary Search is more efficient than Linear Search, but it requires sorted data.
Linear Search works on both sorted and unsorted data.

Q.25: Which sorting algorithm is best if the list is already sorted? Why?

The best sorting algorithm for an already sorted list is Insertion Sort. This is because:

• Time Complexity: For an already sorted list, Insertion Sort performs at its best case
of O(n), which is linear time.
• How it works: In Insertion Sort, during each iteration, the algorithm compares the
current element with the previous one. If the array is already sorted, no swaps are
needed, and the algorithm simply passes through the array once.

Why Insertion Sort is Best:

• Since the array is already sorted, no elements need to be moved, making the algorithm
very efficient for this case.
• Algorithms like Bubble Sort and Selection Sort also perform in O(n) time for sorted
data, but Insertion Sort has the advantage of fewer operations and better performance
in practice.

Q.26: How does the Insertion Sort algorithm work?

Insertion Sort works by repeatedly taking one element from the unsorted part of the array
and inserting it into the sorted part in its correct position.

Steps:

1. Start with the second element of the array.


2. Compare the element with the previous one.
3. If the element is smaller than the one before it, shift the larger element to the right.
4. Insert the element at its correct position.
5. Repeat the process for each element from left to right until the array is sorted.

Example: Array: [5, 3, 8, 4, 2]

1. Start with 3:
o Compare 3 with 5. Since 3 < 5, move 5 to the right and insert 3 at the
beginning.
o Array: [3, 5, 8, 4, 2]
2. Move to 8, which is already in place.
o Array: [3, 5, 8, 4, 2]
3. Move to 4:
o Compare 4 with 8 and shift 8 to the right.
o Compare 4 with 5 and shift 5 to the right.
o Insert 4 in its correct position.
o Array: [3, 4, 5, 8, 2]
4. Finally, insert 2 in its correct position by shifting all larger elements.
o Array: [2, 3, 4, 5, 8]

Q.27: Write a C program to sort the array of object prices from highest to
lowest using an algorithm of your choice. State the algorithm used.

Let's use Selection Sort for sorting the array of object prices in descending order.

Code:

c
Copy code
#include <stdio.h>

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


int i, j, maxIdx, temp;
for (i = 0; i < n-1; i++) {
maxIdx = i;
for (j = i+1; j < n; j++) {
if (arr[j] > arr[maxIdx]) {
maxIdx = j;
}
}
// Swap the found maximum element with the first element
temp = arr[maxIdx];
arr[maxIdx] = arr[i];
arr[i] = temp;
}
}

int main() {
int prices[] = {300, 500, 200, 400, 700};
int n = sizeof(prices) / sizeof(prices[0]);

selectionSortDesc(prices, n);

printf("Sorted prices from highest to lowest:\n");


for (int i = 0; i < n; i++) {
printf("%d ", prices[i]);
}

return 0;
}
Algorithm Used: Selection Sort. It finds the largest element in the unsorted part of the array
and places it at the beginning.

Output:

css
Copy code
Sorted prices from highest to lowest:
700 500 400 300 200

Q.28: Explain how Bubble Sort works to sort an array and how the largest
elements "bubble up" to the end of the list.

Bubble Sort works by repeatedly stepping through the list to be sorted, comparing adjacent
items, and swapping them if they are in the wrong order. After each complete pass through
the list, the largest unsorted element "bubbles up" to its correct position at the end of the
array.

Steps:

1. Start from the first element of the array.


2. Compare the current element with the next element.
3. If the current element is larger than the next element, swap them.
4. After each pass, the largest element is placed at the end of the array.
5. Repeat this process for all elements, but exclude the already sorted elements at the
end.

Example: Array: [5, 3, 8, 4, 2]

1. First pass:
o Compare 5 and 3: Swap them. Array: [3, 5, 8, 4, 2]
o Compare 5 and 8: No swap.
o Compare 8 and 4: Swap them. Array: [3, 5, 4, 8, 2]
o Compare 8 and 2: Swap them. Array: [3, 5, 4, 2, 8]
o The largest element 8 is now in the last position.
2. Second pass:
o Compare 3 and 5: No swap.
o Compare 5 and 4: Swap them. Array: [3, 4, 5, 2, 8]
o Compare 5 and 2: Swap them. Array: [3, 4, 2, 5, 8]
o The second-largest element 5 is now in its correct position.
3. Continue until the array is fully sorted.

Q.29: Describe the insertion sort algorithm to arrange the array elements in
ascending order.

The Insertion Sort algorithm works by iterating through the array and inserting each element
into its correct position in the already sorted part of the array.
Steps:

1. Start with the second element of the array.


2. Compare it with the previous elements and insert it into its correct position in the
sorted part.
3. Repeat this process for each element until the array is sorted.

Example: Array: [3, 1, 4, 5, 2]

1. Start with 1: Compare 1 with 3, shift 3 to the right and insert 1 at the beginning.
Array: [1, 3, 4, 5, 2]
2. Move to 4: It’s already in the correct position. Array: [1, 3, 4, 5, 2]
3. Move to 5: It’s already in the correct position. Array: [1, 3, 4, 5, 2]
4. Move to 2: Shift 5, 4, and 3 to the right and insert 2 at the second position. Array: [1,
2, 3, 4, 5]

Q.30: What is the time complexity of Selection Sort, and why does it remain
the same regardless of the input data?

Time Complexity of Selection Sort:

• Best, Worst, and Average Case: O(n^2)


o In each pass, Selection Sort performs a linear scan to find the smallest element
and swaps it.
o Even if the array is already sorted, the algorithm still performs the same
number of comparisons and swaps.

Why it remains the same:

• The algorithm always goes through the entire array, even if it's already sorted or
nearly sorted. This makes the time complexity O(n^2) in all cases.

Q.31: Apply Insertion Sort to sort an array of negative and positive numbers:
[3, -1, 0, -8, 10, 4]. Show the intermediate steps and sorted output.

Array: [3, -1, 0, -8, 10, 4]

Steps:

1. Start with -1:


o Compare -1 with 3. Swap them. Array: [-1, 3, 0, -8, 10, 4]
2. Move to 0:
o Compare 0 with 3, shift 3 to the right and insert 0. Array: [-1, 0, 3, -8, 10, 4]
3. Move to -8:
o Shift 3, 0, and -1 to the right and insert -8. Array: [-8, -1, 0, 3, 10, 4]
4. Move to 10:
o It’s already in the correct position. Array: [-8, -1, 0, 3, 10, 4]
5. Move to 4:
o Shift 10 to the right and insert 4. Array: [-8, -1, 0, 3, 4, 10]

Sorted Array: [-8, -1, 0, 3, 4, 10]

Q.32: Write a C program to implement Insertion Sort to sort an array of


integers in ascending order. Test the program with the array: [12, 11, 13, 5, 6].
Print the array after each insertion step.

Code:

c
Copy code
#include <stdio.h>

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


int i, j, key;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

// Move elements that are greater than key to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;

// Print the array after each insertion step


printf("After pass %d: ", i);
for (int k = 0; k < n; k++) {
printf("%d ", arr[k]);
}
printf("\n");
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

return 0;
}

Q.33: Perform a dry run of the Insertion Sort algorithm on the following
array: [31, 15, 19, 42, 20]. Show the array's state after each pass.

Array: [31, 15, 19, 42, 20]


1. Start with 15: Compare 15 with 31 and shift 31 to the right, insert 15. Array: [15, 31,
19, 42, 20]
2. Move to 19: Compare 19 with 31 and shift 31 to the right, insert 19. Array: [15, 19,
31, 42, 20]
3. Move to 42: It’s already in the correct position. Array: [15, 19, 31, 42, 20]
4. Move to 20: Compare 20 with 42 and shift 42 to the right, compare 20 with 31 and
shift 31 to the right, insert 20. Array: [15, 19, 20, 31, 42]

Sorted Array: [15, 19, 20, 31, 42]

Q.34: Use Selection Sort to find the smallest and second smallest elements in
the following array: [34, 22, 10, 19, 17].

Array: [34, 22, 10, 19, 17]

1. First pass:
o Find the smallest element (10), swap it with 34. Array: [10, 22, 34, 19, 17]
2. Second pass:
o Find the smallest element in the remaining array (17), swap it with 22. Array:
[10, 17, 34, 19, 22]

Smallest: 10
Second smallest: 17

Q.35: Write a C program to implement Bubble Sort. Sort the following array:
[64, 34, 25, 12, 22, 11, 90] and display the sorted array.

Code:

c
Copy code
#include <stdio.h>

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


int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);

printf("Sorted array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output:

c
Copy code
Sorted array:
11 12 22 25 34 64 90

Q.36: Use Bubble Sort to sort an array of characters. Test the program with:
['e', 'b', 'a', 'd', 'c'] and display the sorted output.

Code:

c
Copy code
#include <stdio.h>

void bubbleSort(char arr[], int n) {


int i, j;
char temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
char arr[] = {'e', 'b', 'a', 'd', 'c'};
int n = sizeof(arr) / sizeof(arr[0]);

bubbleSort(arr, n);

printf("Sorted array of characters: \n");


for (int i = 0; i < n; i++) {
printf("%c ", arr[i]);
}
return 0;
}

Output:

less
Copy code
Sorted array of characters:
a b c d e

Q.37: Write a C program to implement Bubble Sort and sort an array of


integers. Test it on: [34, 12, 45, 2, 10, 6]. Print the array after each pass.

Code:

c
Copy code
#include <stdio.h>

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


int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

// Print array after each pass


printf("After pass %d: ", i+1);
for (int k = 0; k < n; k++) {
printf("%d ", arr[k]);
}
printf("\n");
}
}

int main() {
int arr[] = {34, 12, 45, 2, 10, 6};
int n = sizeof(arr) / sizeof(arr[0]);

bubbleSort(arr, n);

return 0;
}

Output:

mathematica
Copy code
After pass 1: 12 34 2 10 6 45
After pass 2: 12 2 10 6 34 45
After pass 3: 2 10 6 12 34 45
After pass 4: 2 6 10 12 34 45
After pass 5: 2 6 10 12 34 45

Q.38: Evaluate the efficiency of Insertion Sort when sorting a nearly sorted
array versus a completely unsorted array. Compare the number of shifts and
swaps made by your C program in each case.
Explanation:

• Nearly Sorted Array: In Insertion Sort, when the array is nearly sorted, fewer shifts
are needed because each element is already close to its correct position. This leads to
fewer comparisons and shifts.
• Completely Unsorted Array: For an unsorted array, Insertion Sort will perform more
shifts, as each element will need to be compared with multiple elements before being
inserted into its correct position.

Code to compare efficiency:

c
Copy code
#include <stdio.h>

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


int i, j, key, shifts = 0;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

// Shift elements of arr[0..i-1] that are greater than key


while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
shifts++;
}
arr[j + 1] = key;
}
printf("Shifts: %d\n", shifts);
}

int main() {
int nearlySortedArr[] = {1, 2, 3, 4, 5, 6, 7};
int unsortedArr[] = {7, 6, 5, 4, 3, 2, 1};

int n = sizeof(nearlySortedArr) / sizeof(nearlySortedArr[0]);

printf("Efficiency on Nearly Sorted Array:\n");


insertionSort(nearlySortedArr, n);

n = sizeof(unsortedArr) / sizeof(unsortedArr[0]);

printf("\nEfficiency on Unsorted Array:\n");


insertionSort(unsortedArr, n);

return 0;
}

Output:

vbnet
Copy code
Efficiency on Nearly Sorted Array:
Shifts: 0

Efficiency on Unsorted Array:


Shifts: 21
Conclusion: Insertion Sort is more efficient on a nearly sorted array, requiring fewer shifts.

Q.39: Compare the time complexity of Selection Sort and Insertion Sort for
both sorted and unsorted arrays. Implement both algorithms in C and analyze
the number of comparisons and swaps made on the array: [20, 12, 10, 15, 2].

Selection Sort Time Complexity: O(n^2) for both sorted and unsorted arrays, since it always
performs a full scan to find the minimum element in the unsorted part.

Insertion Sort Time Complexity:

• Best Case: O(n) for a sorted array (since no shifts are needed).
• Worst Case: O(n^2) for an unsorted array (due to many shifts).

Code for comparison:

c
Copy code
#include <stdio.h>

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


int i, j, minIdx, temp, comparisons = 0, swaps = 0;
for (i = 0; i < n-1; i++) {
minIdx = i;
for (j = i+1; j < n; j++) {
comparisons++;
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
if (minIdx != i) {
temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
swaps++;
}
}
printf("Selection Sort - Comparisons: %d, Swaps: %d\n", comparisons,
swaps);
}

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


int i, j, key, comparisons = 0, shifts = 0;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key) {


comparisons++;
arr[j + 1] = arr[j];
j = j - 1;
shifts++;
}
arr[j + 1] = key;
if (j >= 0) comparisons++;
}
printf("Insertion Sort - Comparisons: %d, Shifts: %d\n", comparisons,
shifts);
}

int main() {
int arr[] = {20, 12, 10, 15, 2};
int n = sizeof(arr) / sizeof(arr[0]);

int arr1[] = {20, 12, 10, 15, 2};


int arr2[] = {20, 12, 10, 15, 2};

printf("Selection Sort:\n");
selectionSort(arr1, n);

printf("\nInsertion Sort:\n");
insertionSort(arr2, n);

return 0;
}

Output:

yaml
Copy code
Selection Sort - Comparisons: 10, Swaps: 3

Insertion Sort - Comparisons: 9, Shifts: 9

Analysis:

• Selection Sort makes 10 comparisons and 3 swaps regardless of the order of the
array.
• Insertion Sort makes 9 comparisons and 9 shifts in the worst case (unsorted array).

Q.40: Write a C program using Selection Sort to find the k-th smallest
element in an array of integers. Use the array: [23, 12, 31, 17, 46, 5], and find
the 3rd smallest element.

Code:

c
Copy code
#include <stdio.h>

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


int i, j, minIdx, temp;
for (i = 0; i < n-1; i++) {
minIdx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
}

int findKthSmallest(int arr[], int n, int k) {


selectionSort(arr, n);
return arr[k-1]; // 1-based index
}

int main() {
int arr[] = {23, 12, 31, 17, 46, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;

int kthSmallest = findKthSmallest(arr, n, k);


printf("The %d-th smallest element is: %d\n", k, kthSmallest);

return 0;
}

Output:

csharp
Copy code
The 3rd smallest element is: 17

UNIT 5

Q.1: Explain the concept of a stack and its key characteristics.

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This
means that the last element added to the stack is the first one to be removed.

Key Characteristics of a Stack:

1. LIFO Order: The element that is pushed last will be popped first.
2. Push and Pop Operations: The basic operations in a stack are:
o Push: Adds an element to the top of the stack.
o Pop: Removes the element from the top of the stack.
3. Top: Refers to the most recently added element.
4. Overflow and Underflow:
o Overflow: Happens when the stack is full, and an additional element cannot
be added.
o Underflow: Occurs when attempting to pop an element from an empty stack.
5. No Direct Access: Elements can only be accessed from the top, not randomly like in
arrays or linked lists.

Applications of Stack:
• Function Call Stack: Used in programming languages to manage function calls and
return addresses.
• Expression Evaluation: In converting and evaluating expressions like infix to
postfix, or evaluating postfix expressions.

Q.2: What are the applications of a queue?

A queue is a linear data structure that follows the First In, First Out (FIFO) principle. The
first element added to the queue is the first to be removed.

Applications of Queue:

1. Job Scheduling: In operating systems, jobs (processes) are scheduled in a queue to


ensure they are executed in the order they arrive.
2. Printer Queue: Multiple print jobs are managed using a queue to process them in the
order of their arrival.
3. Data Buffering: In data transmission, queues can be used for buffering data between
producer and consumer processes, such as in networking or I/O operations.
4. Breadth-First Search (BFS): In graph algorithms, a queue is used to explore all
nodes level by level.

Q.3: Write a note on dequeue.

A deque (short for Double Ended Queue) is a linear data structure that allows insertion and
deletion of elements from both ends, i.e., both the front and the rear.

Key Characteristics:

1. Insertion and Deletion at Both Ends: Elements can be added or removed from both
the front and rear of the deque.
2. Dynamic Operations: You can perform operations like enqueue and dequeue at both
ends.
3. Types of Deques:
o Input Restricted Deque: Allows deletion from both ends, but insertion is
only allowed at one end.
o Output Restricted Deque: Allows insertion at both ends, but deletion is only
allowed at one end.

Applications:

• Palindrome Checking: A deque can be used to check if a string is a palindrome by


comparing characters from both ends.
• Sliding Window Problems: In problems like calculating the maximum in a sliding
window, a deque can efficiently keep track of elements.
Q.4: What is a stack? Explain any two applications of stack with examples.

A stack is a linear data structure that follows the LIFO (Last In First Out) order. The basic
operations are push (adding an element) and pop (removing an element).

Two Applications of Stack:

1. Expression Evaluation (Postfix Evaluation):


o Example: In a postfix expression, operators follow operands, and the
evaluation is done using a stack. For example, for the expression 2 3 * 5 +:
▪ Push 2 and 3 into the stack.
▪ Pop 3 and 2, multiply them, and push the result (6).
▪ Push 5, then pop 6 and 5, add them, and push the result (11).
▪ Final result is 11.
2. Function Call Stack:
o Example: When a function is called in a program, its execution context
(including local variables and return address) is pushed onto the stack. When
the function finishes execution, the context is popped, and the program control
returns to the calling function.

Q.5: Give the disadvantage of ordinary queue and how it is solved in a


circular queue.

Disadvantage of Ordinary Queue: In an ordinary queue, once the queue is full, no more
elements can be inserted, even if there is space in the front of the queue after some elements
have been dequeued. This is due to the fact that the front of the queue keeps moving forward,
and the rear does not move back, causing unused space.

Solution in Circular Queue: A circular queue solves this problem by connecting the rear of
the queue to the front, effectively using all available space. In a circular queue, when the rear
reaches the end of the array, it wraps around to the beginning if there is space, making better
use of memory.

Q.6: What is a circular queue? Explain how it differs from a linear queue.

A circular queue is a type of queue where the last position is connected back to the first
position, forming a circle. It is used to overcome the issue of wasted space in a linear queue.

Differences between Circular Queue and Linear Queue:

1. Linear Queue:
o Once the rear pointer reaches the end of the queue, no more elements can be
added, even if there is space in the front.
o Example: Inserting elements one by one, and if the queue is full, no more
elements can be added even if there is space in the front.
2. Circular Queue:
o When the rear pointer reaches the end of the queue, it wraps around to the
beginning of the queue if there is space, thus making efficient use of space.
o Example: If there is space at the front after some dequeue operations, new
elements can be added at the front.

Q.7: Write an algorithm for the push operation of a stack with example.

Algorithm for Push Operation:

1. Check if the stack is full (overflow condition).


2. If the stack is not full, increment the top pointer.
3. Insert the element at the position of the top pointer.

Push Operation Algorithm:

text
Copy code
Push(stack, element)
if top == MAX_SIZE - 1 then
print("Stack Overflow")
return
end if
top = top + 1
stack[top] = element
print("Element pushed: ", element)
end Push

Example: Let the stack be represented as stack[5] with a size of 5, initially empty.

• Push(10):
o The top pointer moves to 0, and stack[0] is assigned the value 10.
• Push(20):
o The top pointer moves to 1, and stack[1] is assigned the value 20.

Resulting Stack after two pushes:

arduino
Copy code
stack = [10, 20, _, _, _]

The stack now has two elements: 10 and 20, with the top pointer at index 1.

Q.8: Write a pseudocode for the following queue operations with necessary
declarations.

1. enQueue()
The enQueue() operation inserts an element into the queue.

Pseudocode:
text
Copy code
enQueue(queue, front, rear, element)
if rear == size - 1 then
print("Queue is full")
return
end if
rear = rear + 1
queue[rear] = element
if front == -1 then
front = 0
end if
print("Element enqueued: ", element)
end enQueue

2. deQueue()
The deQueue() operation removes an element from the front of the queue.

Pseudocode:

text
Copy code
deQueue(queue, front, rear)
if front == -1 then
print("Queue is empty")
return
end if
element = queue[front]
if front == rear then
front = rear = -1
else
front = front + 1
end if
print("Element dequeued: ", element)
end deQueue

3. isEmpty()
The isEmpty() operation checks whether the queue is empty.

Pseudocode:

text
Copy code
isEmpty(queue, front)
if front == -1 then
return true
else
return false
end if
end isEmpty

4. isFull()
The isFull() operation checks whether the queue is full.

Pseudocode:

text
Copy code
isFull(rear, size)
if rear == size - 1 then
return true
else
return false
end if
end isFull

5. peek()/front()
The peek() operation returns the front element of the queue without removing it.

Pseudocode:

text
Copy code
peek(queue, front)
if front == -1 then
print("Queue is empty")
return null
else
return queue[front]
end if
end peek

Q.9: Show how queues are represented using arrays.

In array-based queue implementation, the queue is represented by an array, and two variables,
front and rear, are used to keep track of the front and rear of the queue.

Array Representation:

text
Copy code
Queue: [ _ , _ , _ , _ , _ ] // an empty queue with size 5
front = -1
rear = -1

Operations:

1. Enqueue (Insertion):
o Add an element at the rear position, and then increment the rear pointer.
o If front == -1, it indicates the first element has been added, so set front =
0.
2. Dequeue (Deletion):
o Remove an element from the front position, then increment the front
pointer.
o If after removal, front > rear, the queue is empty, so reset both front and
rear to -1.

Example:

• Initial State:
css
Copy code
front = -1, rear = -1, Queue = [ _, _, _, _, _ ]

• After enQueue(10):

css
Copy code
front = 0, rear = 0, Queue = [ 10, _, _, _, _ ]

• After enQueue(20):

css
Copy code
front = 0, rear = 1, Queue = [ 10, 20, _, _, _ ]

• After deQueue:

css
Copy code
front = 1, rear = 1, Queue = [ 10, 20, _, _, _ ]

Q.10: What are the various Operations performed on the Stack?

Operations performed on a stack:

1. Push:
Adds an element to the top of the stack.
2. Pop:
Removes the top element from the stack and returns it.
3. Peek/Top:
Returns the top element of the stack without removing it.
4. isEmpty:
Checks whether the stack is empty.
5. isFull:
Checks whether the stack is full (for bounded stack size).

Q.11: Explain the usage of stack in recursive algorithm implementation.

In recursive algorithms, the function calls are stored in the call stack. Each recursive function
call is pushed onto the stack, and when a function reaches its base case, the call is popped
from the stack, and the control returns to the previous function call.

Example:

• When calculating the factorial of a number using recursion, each recursive call to
factorial(n) pushes the result of the next call onto the stack until n == 1. Then, the
stack starts popping, and the results are returned back.
Advantages:

• The stack allows tracking the state of each function call during recursion and ensures
that control is returned correctly after the function completes.

Q.12: How do you test for an empty Queue?

To test if a queue is empty, we check if the front pointer is equal to -1. If it is, the queue is
empty.

Pseudocode:

text
Copy code
isEmpty(queue, front)
if front == -1 then
return true
else
return false
end if
end isEmpty

Q.13: Write an algorithm for Push and Pop operations on Stack

Push Algorithm:

text
Copy code
Push(stack, top, element)
if top == MAX_SIZE - 1 then
print("Stack Overflow")
return
end if
top = top + 1
stack[top] = element
print("Element pushed: ", element)
end Push

Pop Algorithm:

text
Copy code
Pop(stack, top)
if top == -1 then
print("Stack Underflow")
return
end if
element = stack[top]
top = top - 1
print("Element popped: ", element)
end Pop
Q.14: Explain the addition and deletion operations performed on a circular
queue with necessary algorithms.

Circular Queue Addition (Enqueue) Algorithm:

text
Copy code
enQueue(queue, front, rear, size, element)
if (rear + 1) % size == front then
print("Queue is full")
return
end if
if front == -1 then
front = 0
end if
rear = (rear + 1) % size
queue[rear] = element
print("Element enqueued: ", element)
end enQueue

Circular Queue Deletion (Dequeue) Algorithm:

text
Copy code
deQueue(queue, front, rear)
if front == -1 then
print("Queue is empty")
return
end if
element = queue[front]
if front == rear then
front = rear = -1
else
front = (front + 1) % size
end if
print("Element dequeued: ", element)
end deQueue

Q.15: Write an algorithm to insert an element onto a queue


text
Copy code
enQueue(queue, front, rear, size, element)
if (rear + 1) % size == front then
print("Queue is full")
return
end if
if front == -1 then
front = 0
end if
rear = (rear + 1) % size
queue[rear] = element
print("Element enqueued: ", element)
end enQueue
Q.16: Distinguish between stack and queue

Stack:

• Follows LIFO (Last In, First Out) order.


• Only one end (top) is used for insertion and deletion.
• Operations: push(), pop(), peek(), isEmpty(), isFull().

Queue:

• Follows FIFO (First In, First Out) order.


• Two ends: front for deletion and rear for insertion.
• Operations: enQueue(), deQueue(), isEmpty(), isFull(), peek().

Key Difference:

• Stack operates on the top, while queue operates at both ends: front and rear.

Q.17: Write function definitions for isFull() and Enqueue() functions of


Queue, using given prototypes and declarations for array implementation.
c
Copy code
#define size 5 // Size of the queue

int Queue[size], front = -1, rear = -1;

// Function to check if the queue is full


int isFull() {
if (rear == size - 1) {
return 1; // Queue is full
}
return 0; // Queue is not full
}

// Function to insert an element into the queue


void Enqueue(int element) {
if (isFull()) {
printf("Queue is full\n");
return;
}
if (front == -1) { // If the queue is empty
front = 0;
}
rear = rear + 1; // Move rear pointer to next position
Queue[rear] = element; // Add element to the queue
printf("Element enqueued: %d\n", element);
}

Q.18:
i. State the Data Structure (Stack/Queue) required for conversion of Decimal Number
to its Binary Equivalent.

To convert a decimal number to its binary equivalent, a Stack data structure is typically used.
The process involves repeatedly dividing the decimal number by 2 and pushing the
remainders onto the stack. After the division process is complete, the binary equivalent can
be obtained by popping the elements from the stack.

Why Stack?

• The division process works in reverse order, where the last remainder represents the
highest bit, so a stack (LIFO) is ideal for reversing the order.

ii. ______________ is having a LIFO characteristic.

Stack has a LIFO (Last In, First Out) characteristic. In a stack, the last element added is the
first one to be removed.

iii. peek() function decrements the top (true/false).

False.

The peek() function does not decrement the top of the stack; it simply returns the element at
the current top of the stack without removing it. The top pointer remains unchanged.

iv. enqueue() operation works in constant time. (Yes/No)

Yes.

In a queue, the enqueue() operation typically works in constant time, O(1), as it adds an
element at the rear of the queue without the need for traversing the entire data structure.

v. Chef taking up orders in a restaurant will be served in LIFO order. (True/False)

False.

The chef in a restaurant typically serves orders in FIFO (First In, First Out) order, as the first
order taken is the first one to be served.
Q.19: Define priority queue with diagram and give the operations

A Priority Queue is a type of queue where each element is associated with a priority.
Elements with higher priority are dequeued before elements with lower priority, regardless of
the order in which they were enqueued. Priority queues can be implemented using heaps,
linked lists, or arrays.

Operations:

1. insert(): Inserts an element into the priority queue along with its priority.
2. deleteMin(): Removes the element with the highest priority (smallest element for a
min-heap, largest for a max-heap).
3. peek(): Returns the element with the highest priority without removing it.
4. isEmpty(): Checks whether the priority queue is empty.
5. isFull(): Checks if the priority queue is full (if implemented with a fixed size).

Example (Min-Priority Queue):

markdown
Copy code
5
/ \
8 12
/ \
9 20

In this case, the element 5 has the highest priority (lowest value), so it would be dequeued
first.

Q.20: How do you test for an empty stack?

To test if a stack is empty, we check whether the top pointer is equal to -1. If the top is -1,
the stack is empty.

Pseudocode:

text
Copy code
isEmpty(stack)
if top == -1 then
return true // Stack is empty
else
return false // Stack is not empty
end isEmpty

Q.21: What's the output of this code? Assume all stack functions definitions
are available.

Code:
c
Copy code
#include <stdio.h>

int stack[12];
int top = -1;

int main() {
int i;
for(i = 0; i < 10; i++) {
if(i % 2 == 0)
push(i + 1); // Push even numbers i+1
if(i % 3 == 0)
push(i - 1); // Push numbers i-1 for multiples of 3
}

while(!isempty())
printf("%d\n", pop()); // Print and pop all elements
return 0;
}

Step-by-Step Execution:

1. First loop iteration:


o i = 0:
▪ i % 2 == 0, so push(i + 1) → push(1).
▪ i % 3 == 0, so push(i - 1) → push(-1).
▪ Stack: [-1, 1]
2. Second loop iteration:
o i = 1:
▪ No action for i % 2 == 0 and i % 3 == 0.
3. Third loop iteration:
o i = 2:
▪ i % 2 == 0, so push(i + 1) → push(3).
▪ i % 3 == 0, so push(i - 1) → push(1).
▪ Stack: [-1, 1, 3, 1]
4. Fourth loop iteration:
o i = 3:
▪ i % 2 == 0, so push(i + 1) → push(4).
▪ i % 3 == 0, so push(i - 1) → push(2).
▪ Stack: [-1, 1, 3, 1, 4, 2]
5. Fifth loop iteration:
o i = 4:
▪ i % 2 == 0, so push(i + 1) → push(5).
▪ i % 3 == 0, so push(i - 1) → push(3).
▪ Stack: [-1, 1, 3, 1, 4, 2, 5, 3]
6. Sixth loop iteration:
o i = 5:
▪ i % 2 == 0, so push(i + 1) → push(6).
▪ i % 3 == 0, so push(i - 1) → push(4).
▪ Stack: [-1, 1, 3, 1, 4, 2, 5, 3, 6, 4]
7. Seventh loop iteration:
o i = 6:
▪ i % 2 == 0, so push(i + 1) → push(7).
▪ i % 3 == 0, so push(i - 1) → push(5).
▪ Stack: [-1, 1, 3, 1, 4, 2, 5, 3, 6, 4, 7, 5]
8. Eighth loop iteration:
o i = 7:
▪ No action for i % 2 == 0 and i % 3 == 0.
9. Ninth loop iteration:
o i = 8:
▪ i % 2 == 0, so push(i + 1) → push(9).
▪ i % 3 == 0, so push(i - 1) → push(7).
▪ Stack: [-1, 1, 3, 1, 4, 2, 5, 3, 6, 4, 7, 5, 9, 7]
10. Tenth loop iteration:
o i = 9:
▪ i % 2 == 0, so push(i + 1) → push(10).
▪ i % 3 == 0, so push(i - 1) → push(8).
▪ Stack: [-1, 1, 3, 1, 4, 2, 5, 3, 6, 4, 7, 5, 9, 7, 10, 8]

After the loop ends, the stack contains:


[-1, 1, 3, 1, 4, 2, 5, 3, 6, 4, 7, 5, 9, 7, 10, 8].

Pop Operations:

The while(!isempty()) loop pops and prints elements from the stack. The stack operates in
a LIFO (Last In First Out) manner, so the elements are printed in reverse order of insertion.

The output will be:

text
Copy code
8
10
7
9
5
7
4
6
3
5
2
4
1
3
1
-1

Thus, the output of the program is the elements printed in reverse order of insertion, which
follows the LIFO principle.
Q.22: Write the status of the stack after each operation:

Initial Stack:

• Stack = 10, 20, 30, 40 (TOP = 40)


• Maximum size of the stack = 10

Operations:

1. Push 70
o Stack before: 10, 20, 30, 40
o Push 70 → Add 70 to the top
o Stack after: 10, 20, 30, 40, 70
o TOP = 70
2. Push 100
o Stack before: 10, 20, 30, 40, 70
o Push 100 → Add 100 to the top
o Stack after: 10, 20, 30, 40, 70, 100
o TOP = 100
3. Pop
o Stack before: 10, 20, 30, 40, 70, 100
o Pop → Remove the top element (100)
o Stack after: 10, 20, 30, 40, 70
o TOP = 70
4. Pop
o Stack before: 10, 20, 30, 40, 70
o Pop → Remove the top element (70)
o Stack after: 10, 20, 30, 40
o TOP = 40
5. Push 12
o Stack before: 10, 20, 30, 40
o Push 12 → Add 12 to the top
o Stack after: 10, 20, 30, 40, 12
o TOP = 12
6. Peek
o Stack before: 10, 20, 30, 40, 12
o Peek operation shows the element at the top without removing it.
o Output: 12 (TOP item)
7. Pop
o Stack before: 10, 20, 30, 40, 12
o Pop → Remove the top element (12)
o Stack after: 10, 20, 30, 40
o TOP = 40
8. Push 5
o Stack before: 10, 20, 30, 40
o Push 5 → Add 5 to the top
o Stack after: 10, 20, 30, 40, 5
o TOP = 5
Q.23: Write down the status of the Queue after each of the successive
operations:

Initial Queue:

• Queue = [10, 20, 30, 40] (FRONT = 10, REAR = 40)


• Size of Queue = 10

Operations:

1. enqueue(70)
o Queue before: [10, 20, 30, 40]
o Enqueue 70 → Add 70 to the rear
o Queue after: [10, 20, 30, 40, 70]
o FRONT = 10, REAR = 70
2. dequeue()
o Queue before: [10, 20, 30, 40, 70]
o Dequeue → Remove the FRONT element (10)
o Queue after: [20, 30, 40, 70]
o FRONT = 20, REAR = 70
3. enqueue(80)
o Queue before: [20, 30, 40, 70]
o Enqueue 80 → Add 80 to the rear
o Queue after: [20, 30, 40, 70, 80]
o FRONT = 20, REAR = 80
4. enqueue(90)
o Queue before: [20, 30, 40, 70, 80]
o Enqueue 90 → Add 90 to the rear
o Queue after: [20, 30, 40, 70, 80, 90]
o FRONT = 20, REAR = 90
5. dequeue()
o Queue before: [20, 30, 40, 70, 80, 90]
o Dequeue → Remove the FRONT element (20)
o Queue after: [30, 40, 70, 80, 90]
o FRONT = 30, REAR = 90
6. dequeue()
o Queue before: [30, 40, 70, 80, 90]
o Dequeue → Remove the FRONT element (30)
o Queue after: [40, 70, 80, 90]
o FRONT = 40, REAR = 90

Q.24: Write similarities and differences between Stack and Queue in a tabular
form. Give one real-life situation where each of them can be used.

Aspect Stack Queue


Order of
Last In, First Out (LIFO) First In, First Out (FIFO)
Processing
Aspect Stack Queue
Insertion Push (add element to the top) Enqueue (add element to the rear)
Dequeue (remove element from
Deletion Pop (remove element from the top)
the front)
Only front element can be
Access Only top element can be accessed
accessed
Memory
Static or dynamic allocation Static or dynamic allocation
Allocation
Undo operation in text editor, Queue at a ticket counter, Line in
Real-life Example
Browser history a bank

Q.25: Find the output of the given code. Assume all queue functions are
defined in the code. Show all steps and explain briefly.

Code:

c
Copy code
#include <stdio.h>
int queue[10];
int front = -1;
int rear = -1;

int main() {
int i;
for(i = 0; i < 4; i++) {
if(i % 2 == 0)
enqueue(i + 1);
if(i % 3 == 0)
enqueue(i);
}

while(!is_empty())
printf("%d\n", dequeue());

return 0;
}

Step-by-Step Execution:

1. Initial Values:
o Queue = [] (empty)
o front = -1, rear = -1
2. First loop iteration (i = 0):
o i % 2 == 0: enqueue(1)
o Queue = [1] (front = 1, rear = 1)
o i % 3 == 0: enqueue(0)
o Queue = [1, 0] (front = 1, rear = 0)
3. Second loop iteration (i = 1):
o i % 2 == 0: No action (not divisible by 2)
o i % 3 == 0: enqueue(1)
o Queue = [1, 0, 1] (front = 1, rear = 1)
4. Third loop iteration (i = 2):
o i % 2 == 0: enqueue(3)
o Queue = [1, 0, 1, 3] (front = 1, rear = 3)
o i % 3 == 0: enqueue(2)
o Queue = [1, 0, 1, 3, 2] (front = 1, rear = 2)
5. Fourth loop iteration (i = 3):
o i % 2 == 0: No action (not divisible by 2)
o i % 3 == 0: enqueue(3)
o Queue = [1, 0, 1, 3, 2, 3] (front = 1, rear = 3)
6. Queue State:
o Queue = [1, 0, 1, 3, 2, 3]
o front = 1, rear = 3
7. Dequeueing Elements:
o Dequeue 1 → Queue = [0, 1, 3, 2, 3] → Printed: 1
o Dequeue 0 → Queue = [1, 3, 2, 3] → Printed: 0
o Dequeue 1 → Queue = [3, 2, 3] → Printed: 1
o Dequeue 3 → Queue = [2, 3] → Printed: 3
o Dequeue 2 → Queue = [3] → Printed: 2
o Dequeue 3 → Queue = [] → Printed: 3

Output:

text
Copy code
1
0
1
3
2
3

Q.26: Write function definitions for Enqueue() and Dequeue() functions of a


Queue. Declare all required global variables.

In the queue implementation, we need the following variables:

• front: the index of the first element in the queue.


• rear: the index of the last element in the queue.
• queue[]: an array to store the queue elements.
• size: the maximum number of elements the queue can hold.

Here’s a simple implementation of the Enqueue() and Dequeue() functions:

c
Copy code
#include <stdio.h>
#define SIZE 5 // Define the size of the queue

// Global variables
int queue[SIZE];
int front = -1;
int rear = -1;

// Enqueue function to add an element to the queue


void Enqueue(int value) {
if (rear == SIZE - 1) {
printf("Queue is Full\n");
} else {
if (front == -1) { // If queue is initially empty
front = 0;
}
rear++; // Increment rear to add the element
queue[rear] = value;
printf("Enqueued %d\n", value);
}
}

// Dequeue function to remove an element from the queue


int Dequeue() {
int dequeuedValue;
if (front == -1) {
printf("Queue is Empty\n");
return -1; // Indicating an empty queue
} else {
dequeuedValue = queue[front];
if (front == rear) { // If the queue has only one element
front = rear = -1; // Reset the queue
} else {
front++; // Increment front to remove the element
}
printf("Dequeued %d\n", dequeuedValue);
return dequeuedValue;
}
}

// Main function to test the Enqueue and Dequeue functions


int main() {
Enqueue(10);
Enqueue(20);
Enqueue(30);
Dequeue();
Enqueue(40);
Enqueue(50);
Dequeue();
return 0;
}

Explanation of Functions:

• Enqueue(): Adds an element to the queue. If the queue is full, it prints an error
message. If the queue was initially empty, it initializes the front pointer.
• Dequeue(): Removes an element from the queue. If the queue is empty, it prints an
error message. If the queue becomes empty after a dequeue, both front and rear are
reset to -1.

Q.27: Write an algorithm to check if a given string is a palindrome or not.


Check the working of your algorithm for strings “POP” and “CAT”.
A palindrome is a word, phrase, or sequence that reads the same backward as forward.

Algorithm to check for a palindrome:

1. Start with two pointers: one at the beginning (left) and one at the end (right) of the
string.
2. Compare the characters at the left and right positions.
3. If they match, move the left pointer forward and the right pointer backward.
4. If they do not match, the string is not a palindrome.
5. Repeat this process until the left pointer is greater than or equal to the right pointer.
6. If all characters match, the string is a palindrome.

Algorithm in pseudocode:

sql
Copy code
Function isPalindrome(string):
left = 0
right = length of string - 1

while left < right:


if string[left] != string[right]:
return "Not Palindrome"
left = left + 1
right = right - 1

return "Palindrome"

Example Working:

1. String: "POP"
o left = 0, right = 2
o Compare 'P' and 'P' → Match
o left = 1, right = 1
o Compare 'O' and 'O' → Match
o Since the pointers have crossed, the string is Palindrome.
2. String: "CAT"
o left = 0, right = 2
o Compare 'C' and 'T' → No match
o Therefore, the string is Not Palindrome.

Q.28: What's the output of this code? Assume all stack functions definitions
are available.

Code:

c
Copy code
#include <stdio.h>
int stack[12];
int top = -1;
int main() {
int i;
for(i = 0; i < 10; i++) {
if(i % 2 == 0)
push(i + 1); // Push i + 1 when i is even
if(i % 3 == 0)
push(i - 1); // Push i - 1 when i is divisible by 3
}

while(!isempty()) // While the stack is not empty


printf("%d\n", pop()); // Print popped value

return 0;
}

Step-by-Step Execution:

1. First loop iteration (i = 0):


o i % 2 == 0: push(1) → Stack = [1]
o i % 3 == 0: push(-1) → Stack = [1, -1]
2. Second loop iteration (i = 1):
o i % 2 == 0: No action (not even)
o i % 3 == 0: No action (not divisible by 3)
3. Third loop iteration (i = 2):
o i % 2 == 0: push(3) → Stack = [1, -1, 3]
o i % 3 == 0: push(1) → Stack = [1, -1, 3, 1]
4. Fourth loop iteration (i = 3):
o i % 2 == 0: push(4) → Stack = [1, -1, 3, 1, 4]
o i % 3 == 0: push(2) → Stack = [1, -1, 3, 1, 4, 2]
5. Fifth loop iteration (i = 4):
o i % 2 == 0: push(5) → Stack = [1, -1, 3, 1, 4, 2, 5]
o i % 3 == 0: No action (not divisible by 3)
6. Sixth loop iteration (i = 5):
o i % 2 == 0: No action (not even)
o i % 3 == 0: push(4) → Stack = [1, -1, 3, 1, 4, 2, 5, 4]
7. Stack before popping:
o Stack = [1, -1, 3, 1, 4, 2, 5, 4]
8. Popping:
o Pop 4 → Stack = [1, -1, 3, 1, 4, 2, 5] → Printed: 4
o Pop 5 → Stack = [1, -1, 3, 1, 4, 2] → Printed: 5
o Pop 2 → Stack = [1, -1, 3, 1, 4] → Printed: 2
o Pop 4 → Stack = [1, -1, 3, 1] → Printed: 4
o Pop 1 → Stack = [1, -1, 3] → Printed: 1
o Pop 3 → Stack = [1, -1] → Printed: 3
o Pop -1 → Stack = [1] → Printed: -1
o Pop 1 → Stack = [] → Printed: 1

Output:

diff
Copy code
4
5
2
4
1
3
-1
1

Q.29: i. State the Data Structure (Stack/Queue) required for reversing a


string.

• Stack: A stack is the data structure required to reverse a string. A string is pushed
onto the stack character by character, and then popped out in reverse order.

Q.29: ii. If the first element in is the first element out, then the data structure
is a ____________.

• Queue: A queue follows the First-In-First-Out (FIFO) principle, meaning the first
element added is the first one to be removed.

Q.29: iii. If we want to empty the stack, we will have to repeatedly call _____
function till ______ condition.

• Pop function till stack is empty (i.e., top == -1).

Q.29: iv. dequeue() function operation works in constant time. (Yes/No)

• Yes: In a typical queue, the dequeue() operation works in constant time, O(1), when
using an array or a circular queue.

Q.29: v. When the queue is empty, front = ______ and rear = ______.

• front = -1 and rear = -1. These values indicate that the queue is empty.

Q.30: Stack Operations Output

Let's break down the operations and see the status of the stack after each one:

1. PUSH(10):
o Stack = [10]
o The number 10 is added to the stack. The top of the stack now points to index
0.
2. PUSH(20):
o Stack = [10, 20]
o The number 20 is added to the stack. The top of the stack now points to index
1.
3. POP():
o Stack = [10]
o The top element (20) is removed. The stack now contains only 10. The top of
the stack now points to index 0.
4. PUSH(30):
o Stack = [10, 30]
o The number 30 is added to the stack. The top of the stack now points to index
1.
5. PUSH(40):
o Stack = [10, 30, 40]
o The number 40 is added to the stack. The top of the stack now points to index
2.
6. POP():
o Stack = [10, 30]
o The top element (40) is removed. The stack now contains 10 and 30. The top
of the stack now points to index 1.
7. PUSH(50):
o Stack = [10, 30, 50]
o The number 50 is added to the stack. The top of the stack now points to index
2.
8. PRINT STACK:
o Stack contents are printed in order, starting from the bottom of the stack to the
top:
o Output: 10 30 50

Output of Stack:
Copy code
10 30 50

Q.31: Output of the Given Program

Let's analyze the code step-by-step to understand the output:

Code:

c
Copy code
#include <stdio.h>
#define MAX_SIZE 5

int stack[MAX_SIZE];
int top = -1;
int main() {
for (int i = 0; i < MAX_SIZE; i++) {
stack[++top] = i * 2; // Push elements 0, 2, 4, 6, 8
}

for (int i = 0; i < MAX_SIZE; i++) {


top--; // Pop one element at a time
printf("%d ", stack[top + 1]);
}
return 0;
}

Step-by-step Explanation:

1. First loop (PUSH operations):


o top = -1
o i = 0: stack[++top] = 0 * 2 → stack[0] = 0 → Stack = [0]
o i = 1: stack[++top] = 1 * 2 → stack[1] = 2 → Stack = [0, 2]
o i = 2: stack[++top] = 2 * 2 → stack[2] = 4 → Stack = [0, 2, 4]
o i = 3: stack[++top] = 3 * 2 → stack[3] = 6 → Stack = [0, 2, 4, 6]
o i = 4: stack[++top] = 4 * 2 → stack[4] = 8 → Stack = [0, 2, 4, 6, 8]

After this loop, the stack contains: [0, 2, 4, 6, 8]

2. Second loop (POP operations):


o top = 4 (the last index of the stack)
o i = 0: top-- → top = 3 → Print stack[top + 1] = stack[4] = 8
o i = 1: top-- → top = 2 → Print stack[top + 1] = stack[3] = 6
o i = 2: top-- → top = 1 → Print stack[top + 1] = stack[2] = 4
o i = 3: top-- → top = 0 → Print stack[top + 1] = stack[1] = 2
o i = 4: top-- → top = -1 → Print stack[top + 1] = stack[0] = 0

Output of the program:

Copy code
8 6 4 2 0

Thus, the output will be the stack elements printed in reverse order of their insertion.

Output of the Program:


Copy code
8 6 4 2 0

Q.32: Use Stack to Reverse a String "SUCCESS"

To reverse the string "SUCCESS" using a stack, we can follow these steps:

Step-by-step approach:
1. Push each character of the string onto the stack. The stack follows the Last-In-
First-Out (LIFO) principle, so when we pop the elements from the stack, they will be
in reverse order.
2. Pop each character from the stack and construct the reversed string.

Here is how it works with the string "SUCCESS":

1. Push characters onto the stack:


o Stack: [S] (after pushing 'S')
o Stack: [S, U] (after pushing 'U')
o Stack: [S, U, C] (after pushing 'C')
o Stack: [S, U, C, C] (after pushing 'C')
o Stack: [S, U, C, C, E] (after pushing 'E')
o Stack: [S, U, C, C, E, S] (after pushing 'S')
o Stack: [S, U, C, C, E, S, S] (after pushing 'S')
2. Pop characters from the stack and build the reversed string:
o Pop S → reversed string = "S"
o Pop S → reversed string = "SS"
o Pop E → reversed string = "SSE"
o Pop C → reversed string = "SSEC"
o Pop C → reversed string = "SSEC"
o Pop U → reversed string = "SSECU"
o Pop S → reversed string = "SUCCESS"

Final reversed string: "SUCCESS"

Q.33: Types of Queues with Examples

There are several types of queues:

1. Simple Queue (Linear Queue):


o A linear queue is the simplest type of queue where elements are added at the
rear and removed from the front.
o Example: A queue of people waiting in line at a bank.
2. Circular Queue:
o In a circular queue, the last element points back to the first element. It
efficiently handles the problem of unused space in a linear queue.
o Example: A circular buffer in networking where data is continuously written
and read.
3. Priority Queue:
o In a priority queue, elements are assigned priorities. Elements with higher
priorities are dequeued before elements with lower priorities.
o Example: A hospital emergency room where patients are treated based on the
severity of their conditions rather than their arrival time.
4. Double-Ended Queue (Deque):
o In a deque, elements can be inserted or removed from both ends: front and
rear.
o Example: A browser history where you can go back or forward to visit
previously visited pages.
Q.34: What is Queue? Two Applications

A Queue is a linear data structure that follows the First-In-First-Out (FIFO) principle,
where elements are inserted at the rear and removed from the front.

Applications of Queue:

1. CPU Scheduling:
o In operating systems, queues are used to schedule tasks for CPU processing.
The process that arrives first will be executed first, based on the FIFO
principle.
o Example: Round-robin scheduling in an operating system.
2. Order Processing in Customer Service:
o Queues are used in customer service scenarios, like call centers, where
customers are served in the order they request service.
o Example: A call center where customers are attended to in the order they call.

Q.35: Output of the Given Stack Program

Code:

c
Copy code
#include <stdio.h>
#define MAX_SIZE 5
int stack[MAX_SIZE];
int top = -1;

int main() {
for (int i = 0; i < MAX_SIZE; i++) {
stack[++top] = i * 2;
}
for (int i = 0; i < MAX_SIZE; i++) {
printf("%d ", stack[i]);
}
return 0;
}

Step-by-step Execution:

1. First loop (PUSH operations):


o i = 0: stack[++top] = 0 * 2 → stack[0] = 0 → Stack = [0]
o i = 1: stack[++top] = 1 * 2 → stack[1] = 2 → Stack = [0, 2]
o i = 2: stack[++top] = 2 * 2 → stack[2] = 4 → Stack = [0, 2, 4]
o i = 3: stack[++top] = 3 * 2 → stack[3] = 6 → Stack = [0, 2, 4, 6]
o i = 4: stack[++top] = 4 * 2 → stack[4] = 8 → Stack = [0, 2, 4, 6, 8]
2. Second loop (Print stack):
o Prints the stack contents: 0 2 4 6 8

Output:

Copy code
0 2 4 6 8
Q.36: Pseudocode for Stack Operations

1. push():

arduino
Copy code
Function push(stack, top, element):
if top == MAX_SIZE - 1:
print("Stack Overflow")
return
top = top + 1
stack[top] = element

2. pop():

arduino
Copy code
Function pop(stack, top):
if top == -1:
print("Stack Underflow")
return None
element = stack[top]
top = top - 1
return element

3. isEmpty():

sql
Copy code
Function isEmpty(top):
if top == -1:
return True
else:
return False

4. isFull():

sql
Copy code
Function isFull(top):
if top == MAX_SIZE - 1:
return True
else:
return False

5. peek():

arduino
Copy code
Function peek(stack, top):
if top == -1:
print("Stack is empty")
return None
return stack[top]

Q.37: True/False Statements


1. True: A stack can be implemented using both arrays and linked lists.
2. True: The peek operation in a stack retrieves the top element without removing it.
3. True: Stacks are commonly used in recursive function calls (for managing function
calls in the call stack).
4. False: Infix expressions cannot be directly evaluated using a stack without converting
them into postfix or prefix expressions first.
5. True: A stack can have both overflow and underflow conditions. Overflow occurs
when the stack is full, and underflow occurs when trying to pop from an empty stack.

Q.38: Output of the Given Stack Program

Code:

c
Copy code
#include <stdio.h>
#define MAX_SIZE 4
int stack[MAX_SIZE];
int top = -1;

int main() {
for (int i = 0; i < MAX_SIZE; i++) {
stack[++top] = i + 1; // Pushing values 1, 2, 3, 4
}
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
return 0;
}

Step-by-step Execution:

1. First loop (Push operations):


o Push values: 1, 2, 3, 4 → Stack = [1, 2, 3, 4]
2. Second loop (Print stack in reverse order):
o Prints: 4 3 2 1

Output:

Copy code
4 3 2 1

Q.39: Program to Reverse a Given String

Code to Reverse a String:

c
Copy code
#include <stdio.h>
#include <string.h>

#define MAX_SIZE 100


void reverseString(char str[]) {
int top = -1;
char stack[MAX_SIZE];
int length = strlen(str);

// Push all characters of the string onto the stack


for (int i = 0; i < length; i++) {
stack[++top] = str[i];
}

// Pop all characters and print the reversed string


for (int i = 0; i < length; i++) {
printf("%c", stack[top--]);
}
}

int main() {
char str[] = "HELLO";
reverseString(str);
return 0;
}

Output for "HELLO":

Copy code
OLLEH

Q.40: C Program to Implement Queue Using Array


c
Copy code
#include <stdio.h>
#define SIZE 5

int queue[SIZE];
int front = -1, rear = -1;

int isEmpty() {
return (front == -1);
}

int isFull() {
return (rear == SIZE - 1);
}

void enqueue(int value) {


if (isFull()) {
printf("Queue is Full!\n");
} else {
if (front == -1) front = 0; // First element
queue[++rear] = value;
}
}

void dequeue() {
if (isEmpty()) {
printf("Queue is Empty!\n");
} else {
printf("Dequeued element: %d\n", queue[front]);
if (front == rear) {
front = rear = -1; // Reset after last element
} else {
front++;
}
}
}

void display() {
if (isEmpty()) {
printf("Queue is Empty!\n");
} else {
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}

int main() {
enqueue(10);
enqueue(20);
enqueue(30);
display();
dequeue();
display();
enqueue(40);
enqueue(50);
display();
return 0;
}

Program Behavior:

• Inserts elements into the queue.


• Displays the elements of the queue.
• Removes elements from the front of the queue.
10000 chars

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy