Saturday, March 29, 2014

C program to implement stack using array

C program to implement stack using array

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAXSIZE 10
void push();
int pop();
void traverse();
int stack[MAXSIZE];
int Top=-1;
void main()
{
int choice;
char ch;
do
{
clrscr();
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.TRAVERSE");
printf("\nEnter your Choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:printf("\n The deleted element is %d",pop());
break;
case 3:traverse();
break;
default: printf("\n You entered wrong choice\n");
}
printf("\n Do you want to continue (Y/N\n");
fflush(stdin);
scanf("%c",&ch);
}
while(ch=='Y'||ch=='y');
}
void push()
{
int i;
int item[5];
if(Top==MAXSIZE-1)
 {
printf("The stack is full\n");
getch();
exit(0);
 }
else
 {
printf("Enter the five elements to be inserted");
for (i=0;i<5;i++)
{
scanf("%d",&item[i]);
Top=Top+1;
stack[Top]=item[i];
 }
 }
 }
int pop()
{
int item;
if(Top==-1)
{
printf("The stack is empty");
getch();
exit(0);
}
else
{
item=stack[Top];
Top=Top-1;
}
return(item);
}
void traverse()
{
int i;
if (Top==-1)
{
printf("The stack is Empty");
getch();
exit(0);
}
else
{
for (i=Top;i>=0;i--)
{
//printf("traverse the element");
printf("\n%d",stack[i]);
}
}
}

No comments:

Post a Comment