finding factorial of a number.

this code is to find the factorial of a number by the recursion principle.
trace the control flow in this program very carefully.

``````#include<stdio.h>
main()
{
unsigned long int n,f;
printf("\nenter the number for which you want to find the factorial");
scanf("%d",&n);
f=fact(n);
printf("\nthe factorial of the number %d is %d",n,f);
}
fact(int n)
{
int k;
if(n==0)
return(1);
else
{
k=n*fact(n-1);
}
return(k);
}``````
bumsfeld 413

Interesting code. Corrected a few errors, now it works. However fact(14) is less then fact(13).

for this, i did it with the following code (I have today, Friday 18 April 2008, 3 days coding in C)

``````#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define PI 3.14159265

int main()
{
int i,numero1,f=1;
printf("Number:  ");
scanf("%lf", &numero1);
for(i = 1; i <= numero1; i++)
{
f *= i;
}

}
``````

this is a very basic shortened and NON TESTED version of my working version.

I had to code a calculator for my first semester of university (Im getting a computer degree) for the signature Programming 1.

i think my function, may be a bit primitive, but works flawlessly.

regards,

JLChafardet

yet again, another function for finding the factorial of a number, this time recursive.

``````/* Funcion recursiva para calcular el factorial de un numero */
long long int factorial(long long int n)
{
/* si n es menor que 0, retorna 0 (termina) */
if (n < 0) return 0;
/* o si no, n mayor a 1 retorna n por la funcion misma en n menos 1 */
else if(n > 1) return n*factorial(n-1);
/* retorna un valor para no terminar el programa. */
return 1;
}``````

hope it helps

Just to be sure here that my code worked, i put up a little program and it does. here is the code

``````#include <stdio.h>
#include <stdlib.h>

long long int factorial(long long int n)
{
/* si n es menor que 0, retorna 0 (termina) */
if (n < 0) return 0;
/* o si no, n mayor a 1 retorna n por la funcion misma en n menos 1 */
else if(n > 1) return n*factorial(n-1);
/* retorna un valor para no terminar el programa. */
return 1;
}

int main()
{
printf("\nIngrese El numero al que le quiere sacar el factorial.\n");
printf("Numero:  ");
/* Pide el valor para numero con scanf */
scanf("%llu", &numero);
system("pause");
return 0;
}``````

I just compiled it with Dev-C++ and worked like charm.

I hope this works for others here.

there always occur a prototype error msg in line 7 please clarify