reove main function and cretae simple output
displaying function
Here's the modified code with main() removed and a simple output display function added:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5 // Maximum size of stack
int stack[MAX]; // Global stack array
int top = -1; // top = -1 means empty stack
/* Push Operation */
void push(int value)
{
if(top == MAX - 1)
{
printf("Stack Overflow! Cannot push %d\n", value);
}
else
{
top++;
stack[top] = value;
printf("%d pushed into stack\n", value);
}
}
/* Pop Operation */
int pop()
{
if(top == -1)
{
printf("Stack Underflow! Stack is empty\n");
return -1;
}
else
{
int value = stack[top];
top--;
return value;
}
}
/* Peek Operation */
int peek()
{
if(top == -1)
{
printf("Stack is empty\n");
return -1;
}
else
{
return stack[top];
}
}
/* Display Stack */
void display()
{
if(top == -1)
{
printf("Stack is empty\n");
}
else
{
printf("Stack elements (top to bottom):\n");
for(int i = top; i >= 0; i--)
{
printf("%d\n", stack[i]);
}
}
}
/* ========================================
SIMPLE OUTPUT DISPLAYING FUNCTION
======================================== */
void demo_stack_operations()
{
printf("\n=== STACK DEMO OUTPUT ===\n");
printf("Initial stack: EMPTY\n\n");
// Demo 1: Push operations
printf("1. PUSH OPERATIONS:\n");
push(10);
push(20);
push(30);
display();
// Demo 2: Peek operation
printf("\n2. PEEK (Top element): %d\n", peek());
// Demo 3: Pop operation
printf("\n3. POP OPERATION:\n");
int popped = pop();
if(popped != -1)
printf("Popped: %d\n", popped);
display();
// Demo 4: Overflow test
printf("\n4. STACK OVERFLOW TEST:\n");
push(40);
push(50);
push(60); // This will cause overflow
// Demo 5: Underflow test
printf("\n5. STACK UNDERFLOW TEST:\n");
while(top >= 0)
pop();
pop(); // This will cause underflow
}
How to Use
Save as: stack_library.c
Test in your main program:
#include "stack_library.c" // Include the library
int main()
{
demo_stack_operations(); // Call the demo function
return 0;
}
Sample Output
=== STACK DEMO OUTPUT ===
Initial stack: EMPTY
1. PUSH OPERATIONS:
10 pushed into stack
20 pushed into stack
30 pushed into stack
Stack elements (top to bottom):
30
20
10
2. PEEK (Top element): 30
3. POP OPERATION:
Popped: 30
Stack elements (top to bottom):
20
10
4. STACK OVERFLOW TEST:
40 pushed into stack
50 pushed into stack
Stack Overflow! Cannot push 60
5. STACK UNDERFLOW TEST:
20 popped from stack
10 popped from stack
40 popped from stack
50 popped from stack
Stack Underflow! Stack is empty
Perfect for:
Exam demonstrations
Code reuse as a library
Quick testing of stack operations
Modular programming practice
Now you have a clean stack library with automatic demo output! 🎯