Sunday, 12 March 2017

C program to implement stack using arrays

Stack is a data structure to which the elements are inserted and deleted in the Last In First Out (LIFO). Stack has many applications like arithmetic expression evaluation, subroutine handling, interrupt handling, recursion call implementation etc.. Stack can be implemented statically using arrays or a dynamic stack implementation using Linked list. The following program shows how to implement stack operations using array.

//Program to implement stack using array
#include<stdio.h>
#include<conio.h>
#define size 5

int stack[size],top=-1;

main()
{
 int ch;
 int a;
 void push(int,int *);
 int pop(int *);
 void display();
 clrscr();

 do
 {
  printf("\n1.push\t");
  printf("2.pop\t");
  printf("3.display\t");
  printf("Enter the choice\t");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1: printf("\nEnter the number to be pushed: ");
  scanf("%d",&a);
  push(a,stack);
  break;
   case 2: pop(stack);
  break;
   case 3: display();
  break;
   default: exit(0);
   }
  }while(ch<4);
 getch();
}
void push(int a,int *stack)
{
 if(top>=size)
  {
   printf("Stack overflow\n");
  }
  else
  {
   top++;
   stack[top]=a;
  }
}
int pop(int *stack)
 {
  int temp;
  if(top==-1)
  {
   printf("\nStack Empty\n");
  }
  else
  {
   printf("The popped element is\t");
   {
    temp=stack[top];
    top--;
    printf("%d\n",temp);
    return(temp);
   }
  }
 }
 void display()
 {
  int i;
  if(top==-1)
  {
   printf("Stack underflow\n");
  }
  else
  {
   printf("\nThe contents of the stack are \t");
   for(i=0;i<=top;i++)
   {
    printf("%d\t",stack[i]);
   }
   printf("\n");
  }
 }

/*
OUTPUT
-------

Enter the number to be pushed: 1

1.push  2.pop   3.display       Enter the choice        1

Enter the number to be pushed: 2

1.push  2.pop   3.display       Enter the choice        1

Enter the number to be pushed: 3

1.push  2.pop   3.display       Enter the choice        1

Enter the number to be pushed: 4

1.push  2.pop   3.display       Enter the choice        1

Enter the number to be pushed: 5

1.push  2.pop   3.display       Enter the choice        3

The contents of the stack are   1       2       3       4       5

1.push  2.pop   3.display       Enter the choice        1

Enter the number to be pushed: 6

1.push  2.pop   3.display       Enter the choice        1

Enter the number to be pushed: 7
Stack overflow

1.push  2.pop   3.display       Enter the choice        3

The contents of the stack are   1       2       3       4       5       6


1.push  2.pop   3.display       Enter the choice        2
The popped element is   6

1.push  2.pop   3.display       Enter the choice        2
The popped element is   5

1.push  2.pop   3.display       Enter the choice        2
The popped element is   4

1.push  2.pop   3.display       Enter the choice        4
*/