Stack Program to accept number of operations from user and execute stack operation without using SWITCH statements.

                                                             The C program written below is to execute all stack operation such as PUSH,POP and PEEK but without using switch statement. We can execute following program by using names of that particular operation and at the end we will calculate sum of all remaining elements of Stack....!


#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#define size 50

int stack[size],top = -1,value,k,sum = 0;

void PUSH()

{

    if(top == size-1)

        printf("\nOverflow. Stack is Full");

    else

    {

        scanf("%d",&value);

        top++;

        stack[top] = value;

        printf("\nInsertion was successful");

    }

}

void POP()

{

    if(top == -1)

        printf("\nUnderflow. Stack is empty");

    else

    {

        printf("\nDeleted : %d", stack[top]);

        top--;

    }

}

void PEEK()

{

    if(top == -1)

    {

        printf("\nThe Stack is empty!");

    }

    else

    {

        printf("\nThe top most elememt in stack is :%d",stack[top]);

    }

}

void SUM()

{

    if(top == -1)

    {

        printf("\nNo element found for Addition!!");

    }

    else{

        for(k = 0 ; k < size ; k++)

        {

            sum = sum + stack[k];

        }

        printf("\nSum of all remaining elements in stack is = %d",sum);

    }

}

int main()

{

    int n,i;

    char p[20];

    printf("How many operation you want to perform ?\n");

    scanf("%d",&n);

    printf("\n <---- Enter %d Operations only ---->\n",n);

    for(i = 0; i < n ; i++)

    {

        printf("\n Kindly enter your no. %d Operation :\n",i+1);

        scanf("%s",p);

        if(stricmp(p,"PUSH")==0)

        {

            PUSH();

        }

        else if(stricmp(p,"POP")==0)

        {

            POP();

        }

        else if(stricmp(p,"PEEK")==0)

        {

            PEEK();

        }

        else{

            printf("\n Wrong Choice Entered");

        }

    }

    SUM();

    return 0;

}



INPUT && OUTPUT






Post a Comment

0 Comments