Thursday 9 August 2012

implementation of stack using arrays in c language

#include<stdio.h>
#include<conio.h>
#define max 5
int stack[max],ele,top;
void push();
void pop();
void display();
void topelement();
int main()
{
    char ch;
    top=-1;
    printf("1.push\n2.pop\n3.display\n4.topelement\n5.end\nenter your choice:");
    scanf("%d",&ele);
    do
    {
                    switch(ele)
                    {
                              case 1:
                                   push();
                                   break;
                              case 2:
                                   pop();
                                   break;
                              case 3:
                                   display();
                                   break;
                              case 4:
                                   topelement();
                                   break;
                              case 5:
                                   exit(0);
                                   break;
                    }
             printf("\ndo u want to perform more stack operations[y/n]:");
             ch=_getch();
             if(ch=='y')
             {
                        printf("\n1.push\n2.pop\n3.display\n4.topelement\n5.end\nenter your choice:");
                        scanf("%d",&ele);
             }
    }
    while(ch=='y');
    _getch();
    return 0;
}
void push()
{
     if(top==max-1)
     {
                   printf("stack is full cannot insert anymore\n");
                   return;
     }
     else
     {
                 printf("enter the element do u want to insert:");
                 scanf("%d",&ele);
                 top++;
                 stack[top]=ele;
     }
}
void pop()
{
     if(top==-1)
     {
                printf("stack is empty..no elements to delete\n");
                return;
     }
     else
     {
                top--;
                printf("deleted element from the stack is : %d",stack[top+1]);
     }
}
void display()
{
     int i;
     if(top==-1)
     {
                printf("stack is empty..no elements to display\n");
                return;
     }
     else
     {
         printf("the elememts of the stack are : ");
         for(i=0;i<=top;i++)
                            printf("%d\t",stack[i]);
     }
}
void topelement()
{
     if(top==-1)
     {
                printf("stack is empty\n");
                return;
     }
     else
                printf("the top most element of the stack is : %d",stack[top]);
}

No comments:

Post a Comment