Friday, 27 April 2012

Program for PUSH and POP operations on a Stack in C



#include <stdio.h>
#include<conio.h>
#include<ctype.h>
# define MAX 200

void push(int);
int pop();

int stack[MAX];
int top=-1; // Index is pointing at the top of the stack!
int main()
{
    int x=-1,i,num;
    clrscr();

    while(x !=0)
    {
 printf("\n--------------MAIN MENU------------");
 printf("\n1.Add element to stack\n2.Delete element from the stack\n3.Display stack elements\n4.To exit\n");
 printf("\n\tEnter Choice :: ");
 scanf("%d",&x);

 switch(x)
 {
 case 1:
     printf("Enter the element! ");
     scanf("%d",&num);
     push(num);
     break;
 case 2:
     i=pop();
     printf("%d has been Popped from the Stack.",i);
     break;
 case 3:
     for(i=0;i<=top;i++)
            printf("  %d",stack[i]);
            getch();
            break;
        case 4:
            x = 0;
            break;
        default: printf("Invalid Choice . ");
        }
    }
return 0;
}
 
void push(int y)
{
 
if(top>=MAX-1)
       {
       printf("Stack is FULL! NO MORE SPACE IS AVAILABLE!");
       return;
       }
else
    {
    top++;
    stack[top]=y;
    }
}
 
int pop()
{
int a;
if(top<0)
    {
    printf("Stack is EMPTY! THERE IS NO ELEMENT TO BE DELETED!");
    return 0;
    }
else
    {
    a=stack[top];
    top--;
    }
return(a);
 
}

No comments:

Post a Comment