Name : Vanshika Rajput
E.No : 00289902722
PROGRAM - 5
AIM : Implement two stacks in a using single array.
ALGORITHM :
Step 1 : Start
Step 2 : Define Array and Stack Pointers - Declare an array arr[] to hold elements for both stacks. Define two
pointers top1 and top2 to maintain the top elements of Stack 1 and Stack 2, respectively. Initialize top1 to -1
(indicating an empty stack at the start) and top2 to size (the size of the array, indicating an empty stack at the
beginning).
Step 3 : Push Operation - Function push:
▪ Check if there is space between the two stacks (top1 is less than top2 - 1).
▪ For Stack 1, increment top1 and insert the element at arr[top1].
▪ For Stack 2, decrement top2 and insert the element at arr[top2].
Step 4 : Pop Operation - Function pop:
▪ Check for the stack to pop from.
▪ For Stack 1, return the element at arr[top1] and decrement top1.
▪ For Stack 2, return the element at arr[top2] and increment top2.
Step 5 : Display Stack Elements - Function displayStacks:
▪ Display all elements in Stack 1 from arr[0] to arr[top1].
▪ Display all elements in Stack 2 from arr[size - 1] to arr[top2].
Step 6 : Stop
CODE :
#include <stdio.h>
#define MAX_SIZE 10
int arr[MAX_SIZE];
int top1 = -1;
int top2 = MAX_SIZE;
void push(int stackNumber, int value) {
if (top1 == top2 - 1) {
printf("Stack Overflow!\n");
Name : Vanshika Rajput
E.No : 00289902722
return;
if (stackNumber == 1) {
arr[++top1] = value;
} else if (stackNumber == 2) {
arr[--top2] = value;
} else {
printf("Invalid stack number!\n");
int pop(int stackNumber) {
if (stackNumber == 1) {
if (top1 == -1) {
printf("Stack 1 Underflow!\n");
return -1;
return arr[top1--];
} else if (stackNumber == 2) {
if (top2 == MAX_SIZE) {
printf("Stack 2 Underflow!\n");
return -1;
return arr[top2++];
} else {
printf("Invalid stack number!\n");
return -1;
Name : Vanshika Rajput
E.No : 00289902722
void displayStacks() {
printf("Stack 1 Elements: ");
for (int i = 0; i <= top1; ++i) {
printf("%d ", arr[i]);
printf("\nStack 2 Elements: ");
for (int i = MAX_SIZE - 1; i >= top2; --i) {
printf("%d ", arr[i]);
printf("\n");
int main() {
// Pushing elements into stacks
push(1, 10);
push(2, 20);
push(1, 30);
push(2, 40);
push(2, 50);
// Displaying stack elements
displayStacks();
// Popping elements from stacks
pop(1);
Name : Vanshika Rajput
E.No : 00289902722
pop(2);
// Displaying stack elements after popping
displayStacks();
return 0;
OUTPUT :