Which of the following best explains why a stack data structure is useful?
Think about how you reverse actions or keep track of nested tasks.
A stack stores items so the last one added is the first one removed. This is perfect for undo features and managing function calls where the most recent call must finish first.
What is the printed output after running this C# stack code?
var stack = new System.Collections.Generic.Stack<int>(); stack.Push(10); stack.Push(20); stack.Push(30); Console.WriteLine(stack.Pop()); Console.WriteLine(stack.Peek());
Remember, Pop removes the top item, Peek shows the top item without removing it.
Push adds items on top. The last pushed is 30. Pop removes and returns 30. Peek then shows the new top, which is 20.
What error will this C# code cause when run?
var stack = new System.Collections.Generic.Stack<string>();
stack.Push("first");
stack.Pop();
stack.Pop();Think about what happens if you remove more items than you added.
After popping the only item, the stack is empty. Trying to pop again causes InvalidOperationException because you cannot remove from an empty stack.
Which code snippet correctly uses a stack to reverse the string "hello"?
Pop removes and returns the top item, Peek only returns it without removing.
Option D pushes all characters, then pops each to build reversed string. Option D and D use Peek which does not remove items, causing infinite loop or repeated chars. Option D uses for loop with changing stack.Count, causing incorrect behavior.
Why is a stack the ideal data structure to manage function calls in programming languages?
Think about nested function calls and how the program returns from them.
When a function calls another, the new call is placed on top of the stack. The program must finish the most recent call before returning to previous ones, which is exactly last-in, first-out.
