Wednesday 5 March 2014

Stack implementation using arrays

#include<stdio.h>
#include<stdlib.h>

void push(int S[],int item);
void pop(int S[]);
void displayStack(int S[]);
int top = -1,s_max;

int main(void)
{

        int choice,item;
        printf("\nEnter the Size of the stack : ");
        scanf("%d",&s_max);

        int S[s_max];

        while(1)
        {
        printf("\nEnter the operations choice\n1.Push\n2.Pop\n3.Display Stack\n4.Exit\n\n");
        scanf("%d",&choice);
        switch(choice)
        {
                case 1 :printf("\nEnter the element to push into the stack : ");
                        scanf("%d", &item);
                        push(S,item);
                        //displayStack(S);
                        break;
                case 2 : pop(S);
                        //displayStack(S);
                        break;
                case 3 : displayStack(S);
                         break;
                case 4 : exit(0);
                default:printf("\n\nYou have entered wrong choice !\n\n");
        }
        }
        return 0;

}

void push(int S[],int item)
{
    if(top == s_max-1)
        printf("\n Overflow Error : Stack is full you can't enter any more element.\n");
    else
    {
        top=top+1;
        S[top]=item;
    }
}

void pop(int S[])
{
    if(top == -1)
        printf("\n Underflow Error : Stack is Empty you can't delete any more element.\n");
    else
    {
       top = top-1;
        S[top+1];
        printf("\n%d is poped!\n", S[top+1]);
    }
}

void displayStack(int S[])
{
    int i;
    if(top == -1)
        printf("\nStack is Empty |__| !\n");
    else
    for(i=top; i>=0; i--)
    {
        printf("\t%d\n",S[i]);
    }
}
Output : 

No comments:

Post a Comment