Which of the following best explains why a stack is useful in programming?
Think about how you reverse actions or remember the last thing you did.
A stack follows last-in, first-out (LIFO) order, which is perfect for tracking function calls and undo operations where the most recent action is reversed first.
What is the printed output after running this Rust code that uses a stack?
fn main() {
let mut stack = Vec::new();
stack.push(10);
stack.push(20);
println!("{}", stack.pop().unwrap());
stack.push(30);
println!("{}", stack.pop().unwrap());
println!("{}", stack.pop().unwrap());
}Remember that stack pop removes the last pushed item.
The stack pushes 10, then 20. The first pop removes 20. Then 30 is pushed. The next pop removes 30, and the last pop removes 10.
What error will this Rust code produce when run?
fn main() {
let mut stack = Vec::new();
stack.push(5);
stack.pop();
println!("{}", stack.pop().unwrap());
}Consider what happens when you pop from an empty stack.
After popping once, the stack is empty. Calling pop again returns None, and unwrap on None causes a panic.
Which Rust code snippet correctly uses a stack to reverse the string "hello"?
Think about how popping from a stack reverses order.
Pushing characters onto the Vec (stack) stores them in original order. Option C uses into_iter().rev() to collect from the end (top of stack) first, simulating LIFO pops and reversing "hello" to "olleh".
Why is a stack the ideal data structure for managing function calls in programming languages?
Think about how functions call other functions and then return back.
Function calls are nested. The last function called must finish first before returning to the previous one. A stack naturally supports this last-in, first-out behavior.
