C Program for Stack implementation using Stack

C Program for Stack implementation using Stack:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct stack
{
   int s[5];
   int top;
}stk;

int stfull()
{
   if(stk.top >= 5-1)
      return 1;
   else
      return 0;
}

void push(int item)
{
   stk.top++;
   stk.s[stk.top] = item;
}

int stempty()
{
   if(stk.top == -1)
      return 1;
   else
      return 0;
}

int pop()
{
   int item;
   item = stk.s[stk.top];
   stk.top--;
   return(item);
}

void display()
{
   int i;
   if(stempty())
      printf("\nStack Is Empty!");
   else
    {
      for(i=stk.top;i>=0;i--)
         printf("\n%d",stk.s[i]);
   }
}
main()
{
   int item,choice;
   char ans;
   stk.top = -1;
   do {
      printf("\nMain Menu");
      printf("\n1.Push \n2.Pop \n3.Display \n4.exit");
      printf("\nEnter Your Choice");
      scanf("%d", &choice);
      switch (choice)
      {
      case 1:
         printf("\nEnter the element");
         scanf("%d",&item);
         if(stfull())
            printf("\nStack is Full");
         else
            push(item);
         break;
      case 2:
         if(stempty())
            printf("\nEmpty is stack");
         else
            {
            item = pop();
            printf("\nThe popped element is %d",item);
         }
         break;
      case 3:
         display();
         break;
      case 4:
         exit(0);
      }
      printf("\nDo You want To Continue?");
      ans = getche();
   } while (ans == 'Y' || ans == 'y');
}

OUTPUT:

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 1

Enter the element:5

Do You want To Continue? y

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 1

Enter the element:9

Do You want To Continue? y

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 1

Enter the element:2

Do You want To Continue? y

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 3

2
9
5

Do You want To Continue? y

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 2

The popped element is 2

Do You want To Continue? y

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 3

9
5

Do You want To Continue? n

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.