Thursday, 15 November 2018

Stack Implementation using array

Stack:
Consider a real life example of chair placed one on another first chair can be removed at last
First in Last Out data structure.
Operation on stack:
Top:
Top is a pointer used to locate top most data on stack.
Push: Push/Add data on to stack. Increment top and add data onto position of top
Pop:Pop/remove data from stack. take data in variable then decrement top
Isfull: Check if stack is full or not. check condition Top=>(Size-1)
Isempty: Check if stack is empty or not. check condition Top<=(-1)

  #include<stdio.h>

int stack[50],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
  {
    printf("\n Enter the Choice:");
    scanf("%d",&choice);
   switch(choice)
    {
      case 1:
       {
         push();
         break;
       }
      case 2:
       {
         pop();
         break;
       }
      case 3:
       {
         display();
          break;
       }
       case 4:
       {
         printf("\n\t EXIT POINT ");
         break;
        }
       default:
        {
           printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
         }

    }
  }while(choice!=4);
return 0;
}

//Check first stack is overflow or not .
//Else scan data to be pushed ,increment top and then add data in stack at top pointer lacation
void push()
{
   if(top>=n-1)
     {
      printf("\n\tSTACK is over flow");
     }
   else
     {
       printf(" Enter a value to be pushed:");
       scanf("%d",&x);
       top++;
       stack[top]=x;
     }
}

//First check stack is underflow or not
// Else first take data of pointer top then decrement top pointer. 
void pop()
{
   if(top<=-1)
    {
     printf("\n\t Stack is under flow");
    }
   else
    {
     printf("\n\t The popped elements is %d",stack[top]);
     top--;
    }
}

// For display first check either stack is Empty or not .
// then print data from array pointer starts from top to 0 location.
void display()
{
   if(top>=0)
    {
      printf("\n The elements in STACK \n");
      for(i=top; i>=0; i--)
      printf("\n%d",stack[i]);
      printf("\n Press Next Choice");
    }
   else
    {
      printf("\n The STACK is empty");
    }
 }

 /*
 Output


 Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY
--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
 Enter the Choice:1
 Enter a value to be pushed:56

 Enter the Choice:1
 Enter a value to be pushed:47

 Enter the Choice:1
 Enter a value to be pushed:40

 Enter the Choice:3

 The elements in STACK

40
47
56
 Press Next Choice
 Enter the Choice:2

The popped elements is 40
 Enter the Choice:2

The popped elements is 47
 Enter the Choice:2

The popped elements is 56
 Enter the Choice:2

Stack is under flow
 Enter the Choice:
 */

No comments:

Post a Comment