Stack in C.

 

01  #include<stdio.h>
02
03 #define size 5
04
05 /* stack structure*/
06 struct stack
07
08 {
09 int s[size];
10 int top;
11 }st;
12
13 int stackFull()
14 {
15 if(st.top>=size-1)
16 return 1;
17 else
18 return 0;
19 }
20
21 int stackEmpty()
22 {
23 if(st.top==-1)
24 return 1;
25 else
26 return 0;
27 }
28
29
30 void push(int item)
31 {
32 st.top++;
33 st.s[st.top] =item;
34 }
35
36 int pop()
37 {
38 int item;
39 item=st.s[st.top];
40 st.top --;
41 return(item);
42 }
43
44 void display()
45 {
46 int i;
47 if(stackEmpty())
48 printf("n Stack Is Empty!");
49 else
50 {
51 printf("nElements of Stack : ");
52 for(i=st.top;i>=0;i--)
53 printf(" %d",st.s[i]);
54 }
55 }
56
57
58 int main()
59 {
60 int item,ch;
61
62 st.top=-1;
63
64 printf("n Stack Implementation");
65 do
66 {
67 printf("nn Main Menu");
68 printf("n 1 : Push");
69 printf("n 2 : Pop");
70 printf("n 3 : Display");
71 printf("n 4 : Exit");
72
73 printf("n Select Operation : ");
74 scanf("%d",&ch);
75
76 switch(ch)
77 {
78 case 1:
79 printf("n Enter the item to be pushed : ");
80 scanf("%d",&item);
81
82 if(stackFull())
83 printf("n Stack is Full (Overflow)");
84 else
85 push(item);
86
87 break;
88
89 case 2:
90 if(stackEmpty())
91 {
92 printf("n Stack is Empty (Underflow)");
93 }
94 else
95 {
96 item=pop();
97 printf("n The popped element is %d",item);
98 }
99 break;
100
101 case 3: display();
102 break;
103 case 4:
104 printf("End of Program...");
105
106 }
107 }while(ch!=4);
108 return 0;
109 }
 
 
OUTPUT :


Stack Implementation

Main Menu
1 : Push
2 : Pop
3 : Display
4 : Exit
Select Operation : 1

Enter the item to be pushed : 2


Main Menu
1 : Push
2 : Pop
3 : Display
4 : Exit
Select Operation : 1

Enter the item to be pushed : 4


Main Menu
1 : Push
2 : Pop
3 : Display
4 : Exit
Select Operation : 1

Enter the item to be pushed : 6


Main Menu
1 : Push
2 : Pop
3 : Display
4 : Exit
Select Operation : 3

Elements of Stack : 6 4 2

Main Menu
1 : Push
2 : Pop
3 : Display
4 : Exit
Select Operation : 2


The popped element is 6

Main Menu
1 : Push
2 : Pop
3 : Display
4 : Exit
Select Operation : 3

Elements of Stack : 4 2

Main Menu
1 : Push
2 : Pop
3 : Display
4 : Exit
Select Operation : 4

End of Program...

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *