Wednesday, 4 January 2017

C Program to implement stack using array

Stack is a data structure used in computer programming. Recursive function call is performed with the help of stack. The elements in the stack are accessed Last In First Out (LIFO) order.

//Program to implement stack using arrays
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int sp=-1;
main()
{
  int a[SIZE],i,n,choice;
  int push(int *,int);
  int pop(int *);

  clrscr();
  do
  {
    printf("1. Push\n");
    printf("2. Pop\n");
    printf("3. Display\n");
    printf("4. Quit\n");
    printf("Enter Choice ");
    scanf("%d",&choice);
    switch (choice)
    {
      case 1: printf("Enter element to be pushed into the stack ");
     scanf("%d",&n);
     push(a,n);
     break;

      case 2: n=pop(a);
     if(n!=NULL)
printf("The element popped out from stack is %d\n",n);
     break;

      case 3: if (sp>=0)
     {
printf("Elements in the stack\n");
for(i=sp;i>=0;i--)
  printf("%d\t",a[i]);
     }
     else
     printf("Stack Empty\n");
     break;

      case 4: exit(0);
     break;

      default: printf("wrong choice\n");
   }
   printf("\nDo you want to continue? (1. Yes 2.No)\n");
   scanf("%d",&choice);
  }while (choice==1);
 getch();
}
int push(int *a,int n)
{
   if (sp<SIZE)
      a[++sp]=n;
   else
      printf("Stack Full\n");
   return 1;
}
int pop(int *a)
{
   if (sp==-1)
   {
      printf("Stack empty\n");
      return NULL;
   }
   else
    return a[sp--];
}
/*
OUTPUT
-------
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 1
Enter element to be pushed into the stack 1

Do you want to continue? (1. Yes 2.No)
1
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 1
Enter element to be pushed into the stack 2

Do you want to continue? (1. Yes 2.No)
1
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 1
Enter element to be pushed into the stack 3

Do you want to continue? (1. Yes 2.No)
1
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 3
Elements in the stack
3       2       1
Do you want to continue? (1. Yes 2.No)
1

*/

No comments:

Post a Comment