Saturday, 16 May 2015

C code to implement stack

stack in C
Problem Statement: Write a program in c language to implement stack operation.
i) Push
ii) Pop
iii)Top
iv) Display

Code:

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
# define MAX 10
int top=-1;
double stack_array[MAX];
                                   /*PUSH*/
void push()
{
     double item;
     if(top==(MAX-1))
     printf("stack is over flow:");
     else
     {
         printf("enter the item to be pushed in stack:");
         scanf("%lf",&item);
         top=top+1;
         stack_array[top]=item;
     }
}  /*END OF PUSH*/
                                 /*POP*/
void pop()
{
      if(top == -1)
      {
                 printf("stack overflow!");
      }
                 else
                 {
                     printf("pooped element is %lf\n\n",stack_array[top]);
                     top=top-1;
                 }
}
                                /*TOP*/
void top_data()
{
     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*/
                             /*DISPLAY*/
void display()
{
         int i;
         if(top==-1)
         printf("stack is empty!");
         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;
            }
    }
}


0 comments:

Post a Comment