Recall & Review
beginner Click to reveal answer
What does the
Peek operation do in a stack?The
Peek operation returns the top element of the stack without removing it. It lets you see the last added item while keeping the stack unchanged.beginner Click to reveal answer
In C#, which method is used to look at the top element of a
Stack<T> without removing it?The method is
Peek(). It returns the top item of the stack without changing the stack's contents.intermediate Click to reveal answer
What happens if you call
Peek() on an empty stack in C#?Calling
Peek() on an empty stack throws an InvalidOperationException because there is no element to look at.beginner Click to reveal answer
Why is
Peek() useful compared to Pop() in stack operations?Peek() lets you check the top element without removing it, so you can decide what to do next. Pop() removes the top element, changing the stack.beginner Click to reveal answer
Show a simple C# code snippet to peek the top element of a stack of integers.
var stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
int top = stack.Peek(); // top is 20
Console.WriteLine(top); // prints 20
What does the
Peek() method do in a stack?✗ Incorrect
Peek() returns the top element without removing it, letting you see the last added item.What exception is thrown if
Peek() is called on an empty stack in C#?✗ Incorrect
Calling
Peek() on an empty stack throws InvalidOperationException.Which method removes the top element from a stack?
✗ Incorrect
Pop() removes and returns the top element of the stack.If a stack has elements 5, 10, 15 (15 on top), what does
Peek() return?✗ Incorrect
Peek() returns the top element, which is 15.What is the difference between
Peek() and Pop()?✗ Incorrect
Pop() removes the top element; Peek() only returns it without removal.Explain how the
Peek() operation works on a stack and why it might be useful.Think about looking at the last added item without taking it out.
You got /3 concepts.
Describe what happens if you call
Peek() on an empty stack in C# and how to handle it.Consider safety checks before peeking.
You got /3 concepts.
