Sunday 22 March 2015

Implentation of stack using arrays Using C

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

# define SIZE 10
int arr[SIZE], top = -1, i ;

void push() ;
void pop() ;
void display() ;

void main()
{
int ch ;
clrscr() ;
do
{
printf("\n[1].PUSH [2].POP [3].Display [4].Exit\n") ;
printf("\nEnter your choice [1-4] : ") ;
scanf("%d", &ch) ;
switch(ch)
{
case 1 :
push() ;
break ;
case 2 :
pop() ;
break ;
case 3 :
display() ;
break ;
case 4 :
break ;
default :
printf("\nInvalid option\n") ;
getch() ;
}
} while(ch != 4) ;
getch() ;
}
void push()
{
if(top == SIZE - 1)
{
printf("\nStack is full (overflow)\n") ;
getch() ;
return ;
}
top++ ;
printf("\nEnter the element to PUSH : ") ;
scanf("%d", &arr[top]) ;
}
void pop()
{
if(top == -1)
{
printf("\nStack is empty (underflow)\n") ;
getch() ;
return ;
}
printf("\nThe POP element is : %d\n", arr[top]) ;
getch() ;
top-- ;
}
void display()
{
if(top == -1)
{
printf("\nStack is empty (underflow)\n") ;
getch() ;
return ;
}
printf("\nThe elements in stack are :\n\nTOP") ;
for(i = top ; i >= 0 ; i--)
printf(" -> %d", arr[i]) ;
printf("\n") ;
getch() ;
}

RUN 1 :
~~~~~~~
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 1
Enter the element to PUSH : 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 1
Enter the element to PUSH : 20
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 3
The elements in stack are :
TOP -> 20 -> 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 2
The POP element is : 20
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 3
The elements in stack are :
TOP -> 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 2
The POP element is : 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 2
Stack is empty (underflow)
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 4


No comments:

Post a Comment