Saturday, 17 January 2015

Stack Implementation using Array in C Language


#include
#include
#include
# define MAX 10      // max. stack size defined=10 elements
int top=-1;
double stack_array[MAX];         // stack array contains elements of stack of size max.
                                 
void push()   /*PUSH*/
{
     double item;
     if(top==(MAX-1))
         printf("stack is over flow\n");
     else
     {
         printf("enter the item to be pushed in stack:");
         scanf("%lf",&item);
         top=top+1;
         stack_array[top]=item;
     }
}  /*END OF PUSH*/
                               
void pop()          /*POP*/
{
      if(top == -1)
      {
             printf("stack empty!\n");
      }
      else
      {
             printf("poped element is %lf\n\n",stack_array[top]);
             top=top-1;
      }
}
                             
void top_data()           /*TOP*/
{
     double pushed_item;
     if(top==-1)
     {
          printf("stack empty\n");
     }
     else
     {
       
         printf("\n\t\tThe top item is %.1lf\n",stack_array[top]);
     }
}                   /*END TOP*/
                           
void display()       /*DISPLAY*/
{
         int i;
         if(top==-1)
             printf("stack is empty!\n");
         else
         {
             printf("\tStacked elements:\n");
             for(i=top;i>0;i--)
             {
                    printf("========\n");
                    printf("|  %.1lf  | \n",stack_array[i]);
                    printf("========\n");
           
             }
         }
}
int main()
{
    int ch;
    while(1)
    {
            printf("press 1 for PUSH\n");
            printf("press 2 for POP\n");
            printf("press 3 for Display\n");
            printf("press 4 for TOP\n");
            printf("prres 5 to exit:\n");
            scanf("%d",&ch);
            switch(ch)
            {
                      case 1:
                           push();
                           break;
                      case 2:
                           pop();
                           break;
                      case 3:
                           display();
                           break;
                      case 4:
                           top_data();
                           break;
                      case 5:
                           exit(0);
                           break;
            }
    }
}

How to Run: Run this code using DevC++ compiler.

0 comments:

Post a Comment