Sunday, July 28, 2013

Stack implementation in C

#include<stdio.h>

#define STACKSIZE 20
//stack size is 20
int stack[STACKSIZE]={0};
//top of the stack initially -1 which means empty
int tos=-1;


void push(int ele)
{
 if(tos>=STACKSIZE)
 {
  printf("err: Stack is full\n");
 }
 else
 {
  tos++;
  stack[tos] = ele;    
 }
}

int pop()
{
 if(tos==-1)
 {
  printf("err: stack is empty\n");
 }
 else
 {
  int temp = stack[tos];
  tos--;
  printf("poped element from the stack is %d\n",temp);
  return temp; 
 }
}

void display()
{
 int i;
 for(i=0;i<=tos;i++)
  printf(" %d\n",stack[i]);
 if(tos== -1)
 {
  printf("err: stack is empty\n");
  return;
 }
}
int main()
{

  int ch,ele;
  printf("enter the choice 1-push 2-pop 3-display 9-exit\n");
  scanf("%d",&ch);
  while(ch!=9)
  {
 switch(ch)
 {
  case 1: printf("Enter the ele to push\n");
   scanf("%d",&ele);
   push(ele);
   break;
  case 2: ele = pop();
   break;
  case 3: display();
   break;
  case 4:
   break;
  default:
   break;
 }

  printf("enter the choice 1-push 2-pop 3-display 9-exit\n");
  scanf("%d",&ch);
  }
}


No comments:

Popular Posts