Question 7 of 7advanced✨ CreateLong Answer5 marks

Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user. Display the content of the Stack along with the largest odd number in the Stack. (Hint. Keep popping out the elements from stack and maintain the largest element retrieved so far in a variable. Repeat till Stack is empty)

Correct Answer

python

Program to create a Stack for storing odd numbers

and find the largest odd number

Create an empty stack using list

stack = []

Get numbers from user

n = int(input("How many numbers do you want to enter? ")) print("Enter the numbers:") for i in range(n): num = int(input()) # Push only odd numbers to stack using append() if num % 2 != 0: stack.append(num)

Display the content of stack

print("\nContent of Stack:") for item in stack: print(item)

Find largest odd number by popping elements

if len(stack) == 0: print("Stack is empty, no odd numbers entered") else: largest = stack.pop() # Initialize with first popped element

# Continue popping until stack is empty
while len(stack) > 0:
    item = stack.pop()
    if item > largest:
        largest = item

print("\nLargest odd number in the Stack:", largest)

Sample Output:

How many numbers do you want to enter? 5 Enter the numbers: 4 7 2 9 6

Content of Stack: 7 9

Largest odd number in the Stack: 9

Exercise: EXERCISE | Q: 7 | (Page Page 14)
For More Understanding

Explanation

The program implements a stack using Python list with append() for PUSH operation and pop() for POP operation. Only odd numbers (checked using num % 2 != 0) are pushed into the stack. The content is displayed first, then elements are popped one by one to find the largest odd number. The variable largest stores the maximum value encountered during popping, following the LIFO principle of stack operations.

Solution Steps

  1. Step 1: Create an empty list to implement the stack.

  2. Step 2: Accept numbers from user and push only odd numbers using append().

  3. Step 3: Display all elements currently in the stack.

  4. Step 4: Pop elements one by one and compare with largest variable.

  5. Step 5: Update largest if popped element is greater, continue until stack is empty.

  6. Step 6: Display the largest odd number found.