Cpps Question Bank Ans All Unit
Cpps Question Bank Ans All Unit
Example of a Simple Algorithm: Let’s consider the algorithm to 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
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.
• 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 sum the numbers from 1 to n by iterating over each number
in a loop.
Comparison:
In summary:
Q.5 Define what a conditional approach is. Provide an example where a decision is
required. (5M)
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)
bash
Copy code
Start
Input num1, num2, num3
sum = num1 + num2 + num3
average = sum / 3
Output sum, average
End
Q.8 Draw and briefly explain five symbols commonly used in a flowchart. (5M)
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.
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.
Pseudocode:
mathematica
Copy code
Start
Input price1, price2, price3
total_cost = price1 + price2 + price3
Output total_cost
End
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)
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)
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)
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
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)?"
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)
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)
mathematica
Copy code
Start
Input number n
Set count = 0
While n > 0
count = count + 1
n = n / 10 (integer division)
Output count
End
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)
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)
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)
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
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)
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)
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
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)
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)
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)
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:
Q.33
Finish working on your document
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:
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.
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:
Pseudocode:
vbnet
Copy code
SET number = 3
SET count = 1
WHILE count <= 5 DO
PRINT number * count
count = count + 1
END WHILE
Analysis:
Output:
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:
10000 chars
Pseudocode:
sql
Copy code
IF (x = 10) THEN
PRINT "x is ten"
END IF
Analysis:
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.
Pseudocode:
makefile
Copy code
x = 5
y = x += 3
Analysis:
Final Values:
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.
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.
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:
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:
UNIT 2
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:
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.
python
Copy code
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Output:
Copy code
120
This program uses a loop to multiply the numbers from 1 to 5 and returns the result, which is
120.
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
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.
Where:
For example:
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:
• 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:
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.
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)
Explanation:
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.
Summary of Complexities:
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
Explanation:
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
• 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.
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
Output:
python
Copy code
The reversed number is: 54321
• 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])
• 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.
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:
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:
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:
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:
Pseudocode Analysis:
Formula:
css
Copy code
seed = (a * seed + c) MOD m
Where:
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)
Copy code
3747428591
1849923668
2539266827
1790741614
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:
The smallest divisor (other than 1) is 2, which is the first prime factor.
Steps Involved:
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
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.
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.
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:
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.
• 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:
This formula takes advantage of the fact that the product of the numbers is equal to the
product of their GCD and LCM.
• 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
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.
Copy code
2
2
2
2
2
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.
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.
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;
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:
Where:
Output Calculation: Given the initial seed value of 144, and the constants, the first four
outputs are generated as follows:
1. First Output:
2. Second Output:
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:
Copy code
36664, 49200, 45200, 32768
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.
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 outputs can be computed by following the same steps as in Q.32, applying the new
constants.
To compute the Least Common Multiple (LCM) of a list of numbers, we can use the formula:
We can extend this for a list of numbers by calculating the LCM iteratively.
python
Copy code
import math
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.
python
Copy code
def fibonacci_recursive(n):
if n <= 1:
return n
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
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]
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
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]]]
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
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
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.
Final output: 30
In Python, you can use the random module to generate pseudo-random numbers.
Here’s an example:
python
Copy code
import random
This program generates and prints 10 random integers between 1 and 100 using the randint
function from the random module.
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
UNIT 3
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;
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:
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;
int arr[n];
return 0;
}
Explanation:
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:
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:
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.
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;
// 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];
}
}
return 0;
}
Explanation:
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
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.
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;
return 0;
}
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
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;
int arr[n];
return 0;
}
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
Algorithm:
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.
c
Copy code
#include <stdio.h>
int main() {
int arr[3][3]; // Declare a 3x3 2D array
return 0;
}
Q.15 What will be the output of the program if the array begins at 1200 in
memory?
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:
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
Here are detailed explanations and solutions for your questions related to arrays and matrix
operations:
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:
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"
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.
c
Copy code
#include <stdio.h>
#define MAX 10
int main() {
int mat1[MAX][MAX], mat2[MAX][MAX], result[MAX][MAX], n;
return 0;
}
Q.19 Write a program in C to find the transpose of a given matrix.
c
Copy code
#include <stdio.h>
#define MAX 10
int main() {
int mat[MAX][MAX], result[MAX][MAX], rows, cols;
return 0;
}
Q.20 Write a program in C to accept two matrices and check whether they are
equal.
c
Copy code
#include <stdio.h>
#define MAX 10
int main() {
int mat1[MAX][MAX], mat2[MAX][MAX], rows, cols;
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>
int main() {
int arr[MAX], n;
return 0;
}
Q.22 Write a program in C to merge one sorted array into another sorted
array.
c
Copy code
#include <stdio.h>
int main() {
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 4, 6, 8};
int n1 = 4, n2 = 4;
return 0;
}
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.
c
Copy code
#include <stdio.h>
int main() {
int n;
int arr[n];
// 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;
}
c
Copy code
#include <stdio.h>
void decimalToBinary(int n) {
if (n > 1) {
decimalToBinary(n / 2);
}
printf("%d", n % 2);
}
int main() {
int num;
return 0;
}
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;
int arr[n];
return 0;
}
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}
};
return 0;
}
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.
c
Copy code
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
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
To find the summation of a set of numbers, you simply iterate through the numbers and add
them up.
Algorithm:
Pseudocode:
plaintext
Copy code
1. Initialize sum = 0
2. For each number 'x' in the set:
- sum = sum + x
3. Print sum
The union of two sets is a set that contains all the elements from both sets, with no
duplicates.
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.
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;
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.
Algorithm:
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;
return 0;
}
Explanation:
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:
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.39 Describe the process of converting the binary number 377 to binary.
Perform the conversion and write the final result.
Process:
For 377:
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:
UNIT 4
Q.1 Identify an example where Linear Search might be preferable over
Binary Search.
• 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.
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.
• 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.
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.
• 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.
c
Copy code
#include <stdio.h>
#define MAX 10
int main() {
int first[MAX][MAX], second[MAX][MAX], result[MAX][MAX];
int row1, col1, row2, col2;
if (col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return 0;
}
// Multiply matrices
multiplyMatrices(first, second, result, row1, col1, row2, col2);
return 0;
}
Explanation:
Q.8 List the steps involved in performing a binary search on a sorted array.
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'].
c
Copy code
#include <stdio.h>
int main() {
char arr[] = {'d', 'a', 'c', 'e', 'b'};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, 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.
int main() {
int arr[] = {15, 22, 39, 42, 55, 60};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 42; // Element to search for
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.
Steps:
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:
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.
• 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.
• 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.
Code Snippet:
c
Copy code
#include <stdio.h>
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.
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.
Steps:
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";
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 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.
Steps:
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.
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.
• 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.
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 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>
int main() {
int prices[] = {300, 500, 200, 400, 700};
int n = sizeof(prices) / sizeof(prices[0]);
selectionSortDesc(prices, n);
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. 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 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?
• 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.
Steps:
Code:
c
Copy code
#include <stdio.h>
// 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;
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.
Q.34: Use Selection Sort to find the smallest and second smallest elements in
the following 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>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
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>
int main() {
char arr[] = {'e', 'b', 'a', 'd', 'c'};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
Output:
less
Copy code
Sorted array of characters:
a b c d e
Code:
c
Copy code
#include <stdio.h>
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.
c
Copy code
#include <stdio.h>
int main() {
int nearlySortedArr[] = {1, 2, 3, 4, 5, 6, 7};
int unsortedArr[] = {7, 6, 5, 4, 3, 2, 1};
n = sizeof(unsortedArr) / sizeof(unsortedArr[0]);
return 0;
}
Output:
vbnet
Copy code
Efficiency on Nearly Sorted Array:
Shifts: 0
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.
• 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).
c
Copy code
#include <stdio.h>
int main() {
int arr[] = {20, 12, 10, 15, 2};
int n = sizeof(arr) / sizeof(arr[0]);
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
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>
int main() {
int arr[] = {23, 12, 31, 17, 46, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
return 0;
}
Output:
csharp
Copy code
The 3rd smallest element is: 17
UNIT 5
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.
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.
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:
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:
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).
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.
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.
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.
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
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, _, _, _ ]
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).
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.
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
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.
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
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
Stack:
Queue:
Key Difference:
• Stack operates on the top, while queue operates at both ends: front and rear.
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.
Stack has a LIFO (Last In, First Out) characteristic. In a stack, the last element added is the
first one to be removed.
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.
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.
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).
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.
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:
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.
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:
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:
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.
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
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;
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.
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
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
}
return 0;
}
Step-by-Step Execution:
Output:
diff
Copy code
4
5
2
4
1
3
-1
1
• 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.
• 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.
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
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
}
Step-by-step Explanation:
Copy code
8 6 4 2 0
Thus, the output will be the stack elements printed in reverse order of their insertion.
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.
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.
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:
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]
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:
Output:
Copy code
4 3 2 1
c
Copy code
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "HELLO";
reverseString(str);
return 0;
}
Copy code
OLLEH
int queue[SIZE];
int front = -1, rear = -1;
int isEmpty() {
return (front == -1);
}
int isFull() {
return (rear == SIZE - 1);
}
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: