Sample Output
My Stack Operations
1. Size of stack after push operations: 5
2. Top of the Stack: 12
3. Pop elements from stack : 12 36 4 23 10
4. Size of stack after pop operations : 0
Complete the code
package mystackusingarray;
import java.util.EmptyStackException;
public class MyStackUsingArray {
public int arr[];
public int size;
static public int top = 0;
public MyStackUsingArray(int s) {
size = s;
arr = new int[s];
}
public void push(int element) {
if (isFull()) {
System.out.print("Stack full"); }
else {
Insert statement push operation
}
}
public int pop() {
if (isEmpty()) {
System.out.print("Stack empty");
}
Insert statement pop operation
}
public boolean isEmpty() {
if (top == 0) {
return true;
}
else
return false;
}
public boolean isFull() {
if (top == size) {
return true;
}
else
return false;
}
public int peek() {
Insert statements for peek operation
}
public static void main(String[] args) {
MyStackUsingArray stack = new MyStackUsingArray(10);
statements desired output
package mystackusingarray;
import java.util.EmptyStackException;
public class MyStackUsingArray {
    private int arr[];
    private int size;
    public MyStackUsingArray(int s) {
        size = 0;
        arr = new int[s];
    }
    public void push(int element) {
        if (isFull()) {
            throw new RuntimeException("Stack is full");
        }
        arr[size++] = element;
    }
    public int pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return arr[--size];
    }
    public boolean isEmpty() {
        return size == 0;
    }
    public boolean isFull() {
        return size == arr.length;
    }
    public int peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return arr[size - 1];
    }
    public static void main(String[] args) {
        MyStackUsingArray stack = new MyStackUsingArray(10);
        stack.push(10);
        stack.push(23);
        stack.push(4);
        stack.push(36);
        stack.push(12);
        System.out.println("My Stack Operations");
        System.out.println("1. Size of stack after push operations: " + stack.size);
        System.out.println("2. Top of the Stack: " + stack.peek());
        System.out.print("3. Pop elements from stack: ");
        int size = stack.size;
        for (int i = 0; i < size; i++) {
            System.out.print(stack.pop() + " ");
        }
        System.out.println("\n4. Size of stack after pop operations: " + stack.size);
    }
}
Comments