#include<stdio.h> #include #include<stdlib.h> int stack[10],n=0; int fact(int); int pop(); void push(int); main() { int num; printf("\n FACTORIAL USING STACK IMPLEMENTATED WITH ARRAY\n"); printf("\n Enter a number whose factorial is to be found(1-9): "); scanf("%d",&num); printf("\n The factorial is : %d",fact(num)); getch(); } void display() { int i; printf("\n The stack is :\n"); for(i=1;i<=n;i++) { printf("%d\t",stack[i]); } } int pop() { if(n==0) { printf("\n Stack empty!Pop not possible!"); exit(1); } else { int res=stack[n]; --n; display(); return res; } } void push(int x) { if(n==9) { printf("\n Stack full!Push not possible"); exit(1); } else { n++; stack[n]=x; display(); } }
int fact(int num) { if(num==2) { push(2); push(1); int res=1; display(); while(n>=1) res*=pop(); return res; } else { push(num); return fact(num-1); } }