Friday, September 5, 2008

C code snippet to display array implementation of stack

#include < stdio.h>
#include < conio.h>
#include < process.h>

#define STACK_SIZE 10

void push(int item,int *top,int s[])
{
if(*top==STACK_SIZE-1)
{
printf(" Stack overflow\n");
return;
}

s[++(*top)]=item;
}

int pop(int *top,int s[])
{
int item_deleted;

if(*top==-1)
{
return 0;
}

item_deleted=s[(*top)--];

return item_deleted;
}



void display(int top,int s[])
{
printf(" contents of stack are\n");

for(int i=0;i<= top;i++)
{
printf("%d ",s[i]);
}
}


void main()
{
int top,s[20],choice,item,item_deleted;

top=-1;

for(;;)
{
printf(" 1.Push\n2.Pop\n3.display\n");
printf(" 4.Exit\n");
printf(" Enter choice\n");
scanf(" %d",&choice);

switch(choice)
{
case 1:
printf(" Enter item to be inserted\n");
scanf(" %d",&item);
push(item,&top,s);
break;
case 2:
item_deleted=pop(&top,s);
printf(" The item deleted=%d",item_deleted);
break;
case 3:
display(top,s);
break;
default:
exit(0);
}
}
}

1 comments:

Max said...

Great work... keep it up :)