C Program for Stack Implementation using Array

C Program for Stack Implementation using Array:
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<stdlib.h>
#define size 5
struct stack
{
   int s[size];
   int top;
}stk;

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

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

int stcempty()
{
   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 (stcempty())
      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 (stcfull())
            printf("\nStack is Full!");
         else
            push(item);
         break;
      case 2:
         if (stcempty())
            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.