/****************************
* Umang B Bhatt *
* bhatt.umang7@gmail.com *
*****************************/
/**
* program for factorial using stack
*/
#include<stdio.h>
#include<string.h>
#define MAX 100
// push method
int push(int *s, int top, int ele)
{
int i;
if (top >= MAX)
{
printf("\nStack Overflow");
}
else
{
s[++top] = ele;
}
return top;
}
//pop method
int pop(int *a, int *top)
{
if ((*top) >= 0)
{
(*top) = (*top) - 1;
return a[(*top) + 1];
}
else
{
printf("Stack underflow\n");
return 0;
}
}
// personally, i believe that declaring TOP and S here is bad practice
void main()
{
int n;
int i; // loop variable
int ans = 1 ; // stroes the final answer
int TOP = -1; // stack variables that mainntain stack's top
int s[MAX]; // the stack
printf("\nEnter number: ");
scanf("%d",&n);
// here we can also make sure that the use is not entering a number
// that can not be accomodated in the stack
// if the user enters a number less than or equal to 0
// then we can not find factorial
if(n<=0)
{
printf("\nThe number can not be less than 0");
}
else
{
// push the numbers n,n-1 ....1 in the stack
// you can also go in reverse manner here. the result will be the same
// because in multiplication, order does not matter
for(i = n ; i >0 ; i--)
{
TOP = push(s,TOP, i);
}
// now pop all the elements one by one
// multiply them with the answer variable
while(TOP>=0)
{
ans = ans * pop(s,&TOP);
}
printf("\nFactorail is %d\n",ans);
}
// getch(); // will not work on linux
}
Tuesday, May 3, 2011
factorial using stack
Subscribe to:
Post Comments (Atom)
This comment has been removed by the author.
ReplyDeletewhy did you pass &top instead of top in pop function?? i did not understand
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteAlgorithm used is cool!! :)......Thanks
ReplyDeletehm well good
ReplyDeleteHi Umang your algorithm was wrong ,because I tried this , you have declare top has Google variable,because in pop operation conflicting occurs,during at parameter &top
ReplyDeleteYou have to declare top as global variable
DeleteThis is wrong.You can use underflow condition in else part.You have to check and show it else the computer won't recognise .You can use top-- instead in the else part of statement
ReplyDeleteYou cannot use the underflow condition in the else part.A bit mistake has been made due to my phone's auto correction in the previous comment
ReplyDeleteIt's better to write output also...
ReplyDeleteHey, hi umang this program using of factorial calculation is really help for our studies well. And I find this right blog to get these types of best concepts here.... 🙌
ReplyDeleteThanks
ReplyDelete