C Program for Stack using Array with Stack Structure

C Program for Stack using Array with Stack Structure [Menu Driven]

#include<stdio.h>
#define MAX 10

typedef struct StackArray
{
int arr[MAX];
int top;
}stack;

void initialize(stack *); //prototype declerations
void push(stack *);
void pop(stack *);
void peek(stack *);

void main()
{
stack *s=(stack *)malloc(sizeof(stack)); //pointer variable of stack
int a;

do
{
printf("\nWhat you want to do with stack ?\n");
printf("\n0>Exit\n1>Initialize the array"
"\n2>PUSH to stack\n3>POP from Stack\n4>PEEK the stack\n");
scanf("%d",&a);
      printf("\n\n");
switch(a)
{
case 0:
                          exit(0);
case 1:
initialize(s);
peek(s);
break;
case 2:
push(s); //function calling
printf("\n\n");
peek(s);
break;
case 3:
pop(s);
printf("\n\n");
peek(s);
break;
case 4:
peek(s);
break;
default:
puts("\nWrong choice inputted!enter right choice!\n");
}
         fflush(stdin);
}while(1);
}
void initialize(stack *s) //initialize the stack for the first use
{
int i;
for(i=0; i<MAX; i++)
s->arr[i]=0;
s->top=-1;
}
void push(stack *s) //function definition for push action
{
if(s->top==MAX-1)
printf("\n Stack OVERFLOW!!\n");
else
{
printf("\nEnter data : ");
s->top++;
scanf("%d",&s->arr[s->top]);
}
}
void pop(stack *s) //function definition for Pop action
{
if(s->top==-1)
printf("\n Stack UNDERFLOW!!\n");
else
{
printf("\n Item Popped : %d",s->arr[s->top]);
s->arr[s->top]=0;
s->top--;
}
}
void peek(stack *s) //function definition for display action
{
    int i;
if(s->top==-1)
printf("\nEmpty Stack!\a\n");
else
{
for(i=s->top;i>=0;i--)
printf("%d\n",s->arr[i]);
}
}

The output of the above program:-


What you want to do with stack ?

0>Exit
1>Initialize the array
2>PUSH to stack
3>POP from Stack
4>PEEK the stack
1


Empty Stack!

What you want to do with stack ?

0>Exit
1>Initialize the array
2>PUSH to stack
3>POP from Stack
4>PEEK the stack
2


Enter data : 4

4

What you want to do with stack ?

0>Exit
1>Initialize the array
2>PUSH to stack
3>POP from Stack
4>PEEK the stack
2


Enter data : 5

5
4

What you want to do with stack ?

0>Exit
1>Initialize the array
2>PUSH to stack
3>POP from Stack
4>PEEK the stack
2


Enter data : 6


6
5
4

What you want to do with stack ?

0>Exit
1>Initialize the array
2>PUSH to stack
3>POP from Stack
4>PEEK the stack
3


 Item Popped : 6

5
4

What you want to do with stack ?

0>Exit
1>Initialize the array
2>PUSH to stack
3>POP from Stack
4>PEEK the stack
0