Program opened below. You can scroll through the algorithm, Java code and output.
Program 40
Stack
Question
Implement a stack using an array and provide PUSH, POP and DISPLAY operations.
Algorithm
Step 1: Start the program and declare an integer array to hold the stack elements.
Step 2: Initialise top to -1 to indicate that the stack is empty.
Step 3: Display the menu containing PUSH, POP, DISPLAY and EXIT.
Step 4: Accept the user's menu choice.
Step 5: For PUSH, check whether top has reached the last valid array index.
Step 6: If the stack is full, display an overflow message.
Step 7: Otherwise accept an item, increment top and store the item at that position.
Step 8: For POP, check whether top is -1.
Step 9: If the stack is empty, display an underflow message.
Step 10: Otherwise display the top item and decrement top.
Step 11: For DISPLAY, print the elements from top down to index zero.
Step 12: Repeat the menu until EXIT is selected, then stop.
Java program
Javaimport java.util.*;
class StackArray
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] st = new int[5];
int top = -1, choice, item;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
choice = sc.nextInt();
if (choice == 1)
{
if (top == 4)
{
System.out.println("Stack Overflow");
}
else { System.out.print("Item: ");
item = sc.nextInt();
st[++top] = item;
}
} else if (choice == 2)
{
if (top == -1)
{
System.out.println("Stack Underflow");
}
else
{
System.out.println("Deleted element: " + st[top--]);
}
} else if (choice == 3)
{
if (top == -1)
{
System.out.println("Stack Underflow");
}
else
{
for (int i = top; i >= 0; i--) System.out.println(st[i]);
}
}
} while (choice != 4);
}
}Sample output
Input: Operations: Push 10, Push 20, Display, Pop, Exit
Output: Stack display:
20
10
Deleted element: 20