Advertisement
Shailrshah

Pushing, Popping and Displaying a Stack

Apr 18th, 2013
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h> //required for using malloc() at line 19
  3. int size, count; //Global variables are initialized to 0
  4. void push(int stack[], int value){
  5.     stack[count++] = value;
  6. }
  7. void pop(int stack[]){
  8.     count--;
  9. }
  10. void display(int stack[]){
  11.     if(count == 0) printf("\nThe stack is empty.");
  12.     else for(int i = count-1; i >= 0; i--) printf("%d\n", stack[i]);
  13.     if(count == size) printf("\nThe stack is full.");
  14. }
  15. int main(){
  16.     int choice, n;
  17.     printf("\nEnter the size of the stack: ");
  18.     scanf("%d", &size);
  19.     int *stack = (int*) malloc(sizeof(int) * size); //A better alternative to int stack[100];
  20.     while(1){
  21.         display(stack);
  22.         printf("\n1.Push 2.Pop 3.Exit: ");
  23.         scanf("%d", &choice);
  24.         switch(choice){
  25.             case 1: if(count != size){
  26.                         printf("Enter the number to push: ");
  27.                         scanf("%d", &n);
  28.                         push(stack, n);
  29.                     } else printf("\nError: Overflow\n");
  30.                     break;
  31.             case 2: if(count != 0) pop(stack);
  32.                     else printf("\nError: Underflow.\n");
  33.                     break;
  34.             case 3: return 0;
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement