this video teaches you how to compile C program on Linux (Ubuntu in this case)
and run it
Tuesday, May 3, 2011
factorial using stack
/****************************
* 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
}
Labels:
C,
C program,
factorial,
factorial using stack
Subscribe to:
Posts (Atom)