-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackUsingArray.c
104 lines (89 loc) · 2.04 KB
/
stackUsingArray.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <stdio.h>
#include <stdbool.h>
//global variables
int stack[20], size, item, top=-1; //should change to dynamically allocate size of array and not used 20 as fixed size.
//function prototypes
int push(int item);
int pop();
int display();
int main()
{
int choice;
while(1)
{
printf("Enter size of the stack: \n");
scanf("%d", &size);
if (size>20)
printf("Too big, enter size up till 20");
else
break;
}
while(1)
{
printf("Enter choice, 1->Push, 2->Pop, 3->Display, 4->Exit:\n");
scanf("%d", &choice);
if(choice == 4)
{
printf("Exiting program.\n");
break;
}
switch(choice)
{
case 1:
printf("Enter item to push:\n");
scanf("%d", &item);
choice=push(item);
if(choice)
printf("Successfully pushed %d to the stack.\n", item);
else
printf("Stack overflow!%d", choice);
break;
case 2:
if((item = pop()) != false)
printf("Successfully removed %d from the top of the stack.\n", item);
else
printf("Stack underflow!");
break;
case 3:
if(!display())
printf("Stack is empty.");
break;
default:
printf("Invalid choice.");
}
}
}
int push (int item)
{
if (top == (size-1))
return 0;
else
{
++top;
stack[top]=item;
return 1;
}
}
int pop()
{
if (top==-1)
return false;
else
{
item = stack[top];
--top;
return item;
}
}
int display()
{
if (top==-1)
return 0;
else
{
for (int i=0; i<=top;i++)
printf("%d ", stack[i]);
printf("\n");
return 1;
}
}