Complete the code to declare the array that will hold the stack elements.
private int[] stackArray = new int[[1]];The stack array size should be set using the variable stackSize which defines the maximum capacity of the stack.
Complete the code to check if the stack is empty.
public bool IsEmpty() {
return top [1] -1;
}The stack is empty when top equals -1, meaning no elements are in the stack.
Fix the error in the Push method to correctly add an element to the stack.
public void Push(int value) {
if (top [1] stackSize - 1) {
Console.WriteLine("Stack Overflow");
return;
}
stackArray[++top] = value;
}The stack is full when top is greater than or equal to stackSize - 1. This prevents adding beyond capacity.
Fill both blanks to correctly implement the Pop method that removes and returns the top element.
public int Pop() {
if (top [1] -1) {
Console.WriteLine("Stack Underflow");
return -1;
}
return stackArray[top[2]];
}top instead of decrementing.The stack is empty if top == -1. To pop, return the element at top then decrement top using --.
Complete the code to implement the Peek method that returns the top element without removing it.
public int Peek() {
if (top [1] -1) {
Console.WriteLine("Stack is empty");
return -1;
}
return stackArray[top];
}top when peeking.The Peek method checks if the stack is empty by top == -1. It returns the element at top without changing top, so no increment or decrement is needed (empty string for operator).
