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

int main()
{
    int i=1,fact=1,n;
    printf("enter the no of fact: ");
    scanf("%d",&n);
    factorial(n,fact,i);
    return 0;
}
int factorial(int x,int y,int z)
{
    int r;
    if(x==1)
    {
    r=y*z;
    printf("the fact is %d",r);
    }
    else
    {

        factorial(x--,y*z,z++);
    }


}

hello iam trying recursion using factorial the complier stops working .i dont understand why compiler does that

factorial(x--,y*z,z++);

You're passing the current value of x to factorial(), recursion never stops and you experience a stack overflow.

Also you need to forward-declare your factorial function or define it before the main function.

In addition to what Deceiptikon and sepp2k said, I would add that it yu've declared the function as returning an int value, but at no point to you actually return one.

There is actually a much simpler way to do this, one which takes only the starting value as an argument and returns it's factorial. If you think through the definition of a factorial, it is

N! = N * (N-1)!

which could, as an example, be expanded to get

N! = N * (N - 1) * (N - 2)!
N! = N * (N - 1) * (N - 2) * (N - 3)!
N! = N * (N - 1) * (N - 2) * (N - 3) * (N - 4)!

and so forth, eventually giving

N! = N * (N - 1) * ... 1

meaning that all you need to do to calculate N! is to first calculate (N - 1)!, then multiply that by N. From this, the answer should be straightforward: just re-write the definition into C code.

int factorial(int x)
{
    if (x <= 1)
        return 1;
    else
        return ???   // insert factorial definition here, in C code
}

This should be very easy to understand and implement; I've given you more than enough, too much very likely, and will leave the remaining half a line of code to you.

`

#include<stdio.h>

int factorielle(int n){

    if(n==0){
        return 1;
    }
    else{
    return factorielle(n-1)*n;}

}
main(){

    int result,n;
    printf("Input number: ");
    scanf("%i",&n);
    result=factorielle(n);
    printf("%i! = %i",n,result);


}

How about

int factorial (int n) {
    return n == 0 ? 1 : n * factorial(n-1);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.