Tuesday, July 19, 2011

Program for stack using Array & pointer {push, pop, display}

/*Serial No.153     [swami135.cpp]*/

#include<stdio.h>
#include<conio.h>
#define max 5

void push(int *S, int *top)
    {
    int ele;
    if(*top<max-1)
        {
        (*top)++;
        printf("Enter the element to insert= ");
        scanf("%d",&ele);
        *(S+*top)=ele;
        }
    else
        printf("\nStack is full.\n");
    }

void display_stack(int *S, int top)
    {
    printf("\nElements in the stack are:\n");
    if(top==-1)
        printf("\nStack is empty.\n");
    else
        {
        for(int i=0;i<=top;i++)
            {
            printf("%d ",*(S+i));
            }
        }
    }

void pop(int *S, int *top)
    {
    if(*top==-1)
        printf("\nStack is Empty.You can't pop.\n");
    else
        {
        int value=*(S+*top);
        (*top)--;
        printf("\nElement poped= %d\n",value);
        }
    }

void main()
{
int choice,tos=-1,stack[max];
clrscr();
do
    {
    printf("\n\t[1] Push");
    printf("\n\t[2] Pop");
    printf("\n\t[3] Display");
    printf("\n\t[7] Exit");
    printf("\nEnter your choice= ");
    scanf("%d",&choice);
    switch(choice)
        {
        case 1: push(stack,&tos);
            break;
        case 2: pop(stack,&tos);
            break;
        case 3: display_stack(stack,tos);
        }
    }while(choice!=7);
getch();
}

No comments:

Post a Comment

If you have any doubt, feel free to ask...