Saturday, 4 March 2017

C program to implement stack using array.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
int stack_arr[MAX];
int top=-1;
void push(int item);
int pop();
int peek();
void display();
int full();
int empty();
main()
{
int item,choice;
while(1)
{
   printf("1.Push\n2.Pop\n3.peek\n4.Display\n5.Exit\nEnter your choice:");
   scanf("%d",&choice);
   switch(choice)
     {
     case 1:
       printf("enter elemnt to be pushed:");
               scanf("%d",&item);
               push(item);
               break;
         case 2:
             item=pop();
       printf("popped element is : %d\n",item);
       break;
 case 3:
       item=peek();
printf("top element is : %d\n",item);
break;
 case 4:
       display();
break;
 case 5:
       exit(1);
 default:
       printf("This choice is not present SORRY!!");
     }
}
getch();
}
int full()
{
if(top==MAX-1)
return 1;
else
return  0;
}
int empty()
{
if(top==-1)
return 1;
else
return 0;
}
void push(int item)
{
if(full())
{
printf("its overflow");
exit(1);
}
else
{
top++;
stack_arr[top]=item;
}
}
int pop()
{
int item;
if(empty())
{
printf("its overflow");
exit (1);
}
else
{
item=stack_arr[top];
top--;
return(item);
}
}
int peek()
{
if(empty())
{
printf("its underflow");
exit(1);
}
else
{
return(stack_arr[top]);
}
}
void display()
{
int i;
if(empty())
{
  printf("stack is empty");
  exit(1);
    }
else
{
printf("items are : ");
for(i=top;i>=0;i--)
{
printf("%d  ",stack_arr[i]);
}
printf("\n");
}
}

No comments:

Post a Comment