I'm a begginer in C and had been trying to write a Stack program that can pull/push and display the elements in it. I had been running into some problems that I cannot pinpoint where it roots from. Here's my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_SIZE 100
char ch;
int contents[STACK_SIZE], top = 0;
void display();
int stack_overflow(void)
{
printf("Expression is too complex\n");
exit(EXIT_FAILURE);
}
int stack_underflow(void)
{
printf("Not enough operands in expression\n");
exit(EXIT_FAILURE);
}
void make_empty(void)
{
top = 0; //makes the element at the top of the stack = 0
}
bool is_empty(void)
{
return top == 0; //returns 1 if the top is equal to 0
}
bool is_full(void)
{
return top == STACK_SIZE; //returns 1 if the top is the maximun stack size (already full)
}
void push(char i)
{
if (is_full())
stack_overflow();
else
contents[top++] = i;
}
char pop(void)
{
if (is_empty())
stack_underflow();
else
return contents[--top];
}
int main(void)
{
int choice;
int option = 1;
int num;
printf ("STACK OPERATION\n");
while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1: printf("Enter number you want to push: ");
scanf("%d",&num);
push(num);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
void display()
{
int i;
printf("\n\n");
for(i=0;i< top ;i++)
printf("%d\n",contents[i]);
}
STACK OPERATION
------------------------------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
------------------------------------------
Enter your choice
1
Enter number you want to push: 100
Do you want to continue(Type 0 or 1)?
1
------------------------------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
------------------------------------------
Enter your choice
1
Enter number you want to push: 500
Do you want to continue(Type 0 or 1)?
1
------------------------------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
------------------------------------------
Enter your choice
3
100
-12
Do you want to continue(Type 0 or 1)?
0
Process returned 0 (0x0) execution time : 11.474 s Press any key to continue.
Seems like it's not storing the elements correctly or maybe It's printing them wrong. Maybe using the top variable to ran through the loops is wrong? Any help would be much appreciated.