Skip to content
Exercises · Q7

Q.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)

Tripura TbseTextbookSubjective· 3mImportance★★★★★
69% · 9/13 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

This program uses a Python list as a stack to collect only odd numbers entered by the user, then pops all elements to find and display the largest odd number.

Why a Stack with a Traversal to Find the Maximum?

The question asks for two things: store odd numbers in a stack, and then find the largest among them. A stack is a LIFO (Last In, First Out) data structure — you can only access the top element directly. To examine every element, you must pop them one by one until the stack is empty. That's exactly what the hint suggests: pop each element, compare it with a running maximum variable, and update that variable whenever you find a larger number.

This is a classic "stack traversal with aggregation" pattern. You cannot simply iterate over a stack like a list (though in Python a list-based stack could be indexed — but that defeats the purpose of learning stack operations). The proper stack discipline is: push to add, pop to remove and inspect. The hint guides you to use pop() in a loop, which is the correct stack-based approach.

Watch out

A common mistake is to use max(stack) directly on the list. While that works in Python, it bypasses the stack traversal concept the question is testing. Always pop elements one by one as the hint specifies.

The Program

# Create an empty stack (using a Python list)
stack = []

# Get numbers from the user
print("Enter numbers (type 'done' to stop):")
while True:
    user_input = input("Enter a number: ")
    if user_input.lower() == 'done':
        break
    try:
        num = int(user_input)
        # Push only odd numbers onto the stack
        if num % 2 != 0:
            stack.append(num)
    except ValueError:
        print("Invalid input. Please enter an integer or 'done'.")

# Display the stack contents
print("\nStack contents (top to bottom):")
# To show top-to-bottom, we reverse the list for display
for item in reversed(stack):
    print(item)

# Find the largest odd number by popping all elements
if not stack:
    print("\nNo odd numbers were entered.")
else:
    largest = None
    print("\nPopping elements to find the largest odd number...")
    while stack:
        current = stack.pop()
        print(f"Popped: {current}")
        if largest is None or current > largest:
            largest = current
    
    print(f"\nThe largest odd number in the stack was: {largest}")

Key Lines Explained

  • stack = [] — We use a Python list as our stack. append() acts as push(), and pop() removes the last element (LIFO).
  • if num % 2 != 0: — The modulo operator checks if the number is odd. Only odd numbers are pushed. …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.