We need these header files...
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
Let's define some constants...
// constants
#define MAX 5 // Max capacity of a stack
#define ERR "\x1B[31m" // Error Color
#define SUCCESS "\x1B[32m" // Success Color
#define RESET "\033[0m" // Reset Color
Constants defined in above lines of code such as ERR
,SUCCESS
and RESET
will be used to color the text of printf()
. MAX
defines the maximum capacity of the stack
Now we'll declare a stack...
//declaration of stack
typedef struct stack
{
int entry[MAX];
int top;
} stack;
Initialization of stack
//stack initialization
void init(stack *sptr)
{
sptr->top = 0;
}
A function to check if Stack is empty...
//checking stack is empty or not.
int isEmpty(stack *sptr)
{
if (sptr->top == 0)
return (1);
else
return (0);
}
A function to check if stack is overflowed...
//checking stack is full or not.
int isFull(stack *sptr)
{
if (sptr->top == MAX)
return (1);
else
return (0);
}
A function to push/insert a new element into the stack...
//Inserting element into stack
void push(stack *sptr)
{
int item;
if (isFull(sptr))
printf(ERR "\tSTACK IS FULL" RESET);
else
{
printf("\n\tEnter the element: ");
scanf("%d", &item);
sptr->entry[sptr->top] = item;
sptr->top++;
}
}
A function to pop/remove elements from the stack...
//Deleting element from the stack
void pop(stack *sptr)
{
int item;
if (isEmpty(sptr))
printf(ERR "\tSTACK IS EMPTY" RESET);
else
{
sptr->top--;
item = (sptr->entry[sptr->top]);
printf(SUCCESS "\t%d HAS BEEN REMOVED" RESET, item);
}
}
A function to traverse though the stack or print all the elements of the stack
//Traversing the elements of stack
void traverse(stack *sptr)
{
if (isEmpty(sptr))
printf(ERR "\tSTACK IS EMPTY" RESET);
else
{
int i;
for (i = sptr->top - 1; i >= 0; i--)
printf("\t-> %d\n", sptr->entry[i]);
}
}
And finally the main()
function...
int main()
{
stack s;
int choice;
init(&s);
do
{
printf("\n 1. PUSH");
printf("\n 2. POP");
printf("\n 3. TRAVERSE");
printf("\n 4. EXIT");
printf("\n\nEnter the choice: ");
scanf(" %d", &choice);
switch (choice)
{
case 1:
push(&s);
break;
case 2:
pop(&s);
break;
case 3:
traverse(&s);
break;
case 4:
exit(0);
break;
default:
printf(ERR "\tWRONG CHOICE" RESET);
}
} while (1);
return 0;
getch();
}
Output
Pushed 5 elements to the stack. (max capacity=5)
Removed two elements from the stack
Removed all elements until the stack is empty
Top comments (2)
You can do this btw
I think you shouldn't do traverse in stack.
Yes, I do agree with you. Thanks for correction!