Write a C program to implement a dynamic stack.
Write menu driven program to perform following
operations on a stack –
a. Initialize a stack
b. Push an element into a stack
c. Pop an element from stack
d. Display a stack
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack {
int *data;
int top;
int capacity;
} Stack;
// Function to initialize the stack
void initStack(Stack *stack) {
stack->capacity = 1;
stack->top = -1;
stack->data = (int *)malloc(stack->capacity * sizeof(int));
if (!stack->data) {
printf("Memory allocation failed!\n");
exit(1);
printf("Stack initialized successfully.\n");
}
// Function to resize the stack dynamically
void resizeStack(Stack *stack) {
stack->capacity *= 2;
stack->data = (int *)realloc(stack->data, stack->capacity * sizeof(int));
if (!stack->data) {
printf("Memory reallocation failed!\n");
exit(1);
// Function to push an element into the stack
void push(Stack *stack, int element) {
if (stack->top == stack->capacity - 1) {
resizeStack(stack);
stack->data[++stack->top] = element;
printf("%d pushed into the stack.\n", element);
// Function to pop an element from the stack
void pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack underflow! No elements to pop.\n");
return;
int poppedElement = stack->data[stack->top--];
printf("%d popped from the stack.\n", poppedElement);
// Function to display the stack elements
void display(Stack *stack) {
if (stack->top == -1) {
printf("The stack is empty.\n");
return;
printf("Stack elements: ");
for (int i = 0; i <= stack->top; i++) {
printf("%d ", stack->data[i]);
printf("\n");
// Function to free stack memory
void freeStack(Stack *stack) {
free(stack->data);
printf("Stack memory freed.\n");
// Main menu-driven program
int main() {
Stack stack;
int choice, element;
while (1) {
printf("\nMenu:\n");
printf("1. Initialize Stack\n");
printf("2. Push Element\n");
printf("3. Pop Element\n");
printf("4. Display Stack\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
initStack(&stack);
break;
case 2:
printf("Enter element to push: ");
scanf("%d", &element);
push(&stack, element);
break;
case 3:
pop(&stack);
break;
case 4:
display(&stack);
break;
case 5:
freeStack(&stack);
exit(0);
default:
printf("Invalid choice! Please try again.\n");
return 0;