Consider the following C# code that uses a stack. What will be printed after peeking the top element?
using System; using System.Collections.Generic; class Program { static void Main() { Stack<int> stack = new Stack<int>(); stack.Push(10); stack.Push(20); stack.Push(30); Console.WriteLine(stack.Peek()); } }
Peek returns the last pushed item without removing it.
The stack has elements pushed in order: 10, 20, 30. The top is the last pushed, 30. Peek returns 30 without removing it.
What will happen if you call Peek() on an empty stack in C#?
using System; using System.Collections.Generic; class Program { static void Main() { Stack<int> stack = new Stack<int>(); Console.WriteLine(stack.Peek()); } }
Peek on empty stack throws an exception.
Calling Peek on an empty stack throws InvalidOperationException because there is no element to return.
What error will this code produce when trying to peek the top element?
using System; using System.Collections.Generic; class Program { static void Main() { Stack<string> stack = new Stack<string>(); stack.Push("apple"); stack.Push("banana"); stack.Pop(); stack.Pop(); Console.WriteLine(stack.Peek()); } }
After popping all elements, the stack is empty.
Both elements are popped, so the stack is empty. Peek on empty stack throws InvalidOperationException.
What is the content of the stack after peeking the top element?
using System; using System.Collections.Generic; class Program { static void Main() { Stack<int> stack = new Stack<int>(); stack.Push(5); stack.Push(15); int top = stack.Peek(); Console.WriteLine(string.Join(", ", stack)); } }
Peek does not remove the top element.
Peek returns the top element but does not remove it. The stack remains with 15 on top, then 5.
Choose the correct statement about the Peek operation on a stack.
Peek only looks at the top element without changing the stack.
Peek returns the top element without removing it. If the stack is empty, it throws InvalidOperationException.
