Complete the code to push an element onto the stack using array indexing.
int stack[5]; int top = -1; // Push 10 onto stack stack[++[1]] = 10;
We use top to track the current top index of the stack. Incrementing top and assigning the value pushes the element.
Complete the code to check if the stack is empty before popping.
if ([1] == -1) { // Stack is empty std::cout << "Stack Underflow" << std::endl; }
The top variable is -1 when the stack is empty, so we check top == -1.
Fix the error in the pop operation to correctly return the top element and update the stack.
int pop() {
if (top == -1) {
std::cout << "Stack Underflow" << std::endl;
return -1;
}
return stack[[1]--];
}We return the element at stack[top] and then decrement top to remove it from the stack.
Fill the blank to implement a function that checks if the stack is full.
bool isFull() {
return top == [1] - 1;
}The stack is full when top equals capacity - 1. The capacity variable stores the maximum size.
Fill all three blanks to create a function that pushes an element if the stack is not full.
void push(int value) {
if (top == [1] - 1) {
std::cout << "Stack Overflow" << std::endl;
return;
}
stack[++[2]] = [3];
}We check if top == capacity - 1 to detect overflow. Then increment top and assign the value to the stack.
