Advertisement
Shailrshah

Array Implementation of Stacks

Sep 1st, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int size, count; //count represents number of elements in the stack
  4. int* create(int size){
  5.     printf("\nA stack of size %d is being created.", size);
  6.     return (int*) malloc(sizeof(int) * size);//size to be allocated = size of int * no. of ints
  7. }
  8. void push(int stack[], int value){
  9.     stack[count++] = value;
  10. }
  11. void pop(int stack[]){
  12.     count--;
  13. }
  14. void display(int stack[]){
  15.     if(count == 0) printf("\nThe stack is empty.");
  16.     else for(int i = count-1; i >= 0; i--) printf("%d\n", stack[i]);//display from to to bottom
  17.     if(count == size) printf("\nThe stack is full.");
  18. }
  19. int main(){
  20.     int choice, n;
  21.     int *stack = NULL;
  22.     printf("\nEnter the size of the stack: ");
  23.     scanf("%d", &size);
  24.     stack = create(size);
  25.     while(1){
  26.         display(stack);
  27.         printf("\n1.Push 2.Pop 3.Exit: ");
  28.         scanf("%d", &choice);
  29.         switch(choice){
  30.             case 1: if(count != size){//If the stack is not full
  31.                         printf("Enter the number to push: ");
  32.                         scanf("%d", &n);
  33.                         push(stack, n);
  34.                     } else printf("\nError: Overflow\n");
  35.                     break;
  36.             case 2: if(count != 0) pop(stack);
  37.                     else printf("\nError: Underflow.\n");
  38.                     break;
  39.             case 3: return 0;
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement