Sunday, April 1, 2012

stack using array

#include< stdio.h> 

int stack[10],top,element,choice;

void push();
void pop();
void display();
int menu();
int empty();


void main()
{
 top=-1;
 while(1)
 {
  choice=menu();
  switch(choice)
  {
   case 1: push();
    getch();
    break;
   case 2: pop();
    getch();
    break;
   case 3: printf("\nno. of stack elements : %d\ndisplaying current stack :\n\n",top+1);
    display();
    getch();
    break;
   case 4: exit();
   default: printf("\ninvalid option... \n");
     getch();
  }
 }
}

int menu()
{
 int a=0;
 clrscr();
 printf("Stack of 10 elements : \n\n");
 display();
 printf("\n\nMENU\n-------------\n");
 printf("1. push\n2. pop\n3. display\n4. exit\nenter an option : ");
 scanf("%d",&a);
 return a;
}

void push()
{
 if(empty()==0)
  return;
 else
 {
  top++;
  printf("\nenter element to push : ");
  scanf("%d",&element);
  stack[top]=element;
 }
}
void pop()
{
 if(empty()==1)
  return;
 else
 {
  top--;
  printf("\nelement poped from stack\n");
 }
}
void display()
{
 int temp;
 temp=top;

 if(empty()==1)
  return;
 else
 {
  while(temp>-1)
  {
   printf("%d ",stack[temp]);
   temp--;
  }
 }
}
int empty()
{
 if(top==-1)
 {
  printf("\nstack is empty\n");
  return 1;
 }
 else if(top>9)
 {
  printf("\nstack is full\n");
  return 0;
 }
 else
  return 5;
}

No comments:

Post a Comment