Stack using array code with output

Code

#include<stdio.h>

#define SIZE 5

typedef struct 
{
        int top,arr[SIZE];
}stack;

stack s;

void init()
{
    s.top = -1;
}

int isEmpty()
{
    if(s.top==-1)
        return 1;
    return 0;
}

void push()
{
    int element;
    do
    {
        if(s.top==(SIZE-1))
        {
            printf("Stack full");
            break;
        }

        printf("Enter element to be pushed ");
        scanf("%d",&element);

        s.arr[++s.top] = element;

        printf("Push more elements ? ");

        fflush(stdin);
    }while(getchar()=='y');
}   

int pop()
{
    if(isEmpty())
    {
        printf("Stack is empty.Can't pop.");
        return -1;
    }

    return s.arr[s.top--];
}

void display()
{
    int i;

    if(isEmpty())
    {
        printf("\nStack is Empty");
        return;
    }

    printf("  top-->");

    for(i=s.top;i>=0;i--)
        printf("%d\n\t",s.arr[i]);

}


int main()
{
    int ch,element;

    init();

    do
    {
        printf("\n1.Push\n2.Pop\n3.Display\nEnter choice ");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1:
                    push();
                    break;

            case 2:
                    element = pop();   
                    if(element!=-1)printf("\nPopped element = %d",element);   
                    break;

            case 3:
                    display();
                    break;
        }
        printf("\nContinue ? ");
        fflush(stdin);
     }while(getchar()=='y');

    return 0;
}



No comments:

Post a Comment