We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,787 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

factorial using recursion

#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

4
Contributors
3
Replies
2 Hours
Discussion Span
9 Months Ago
Last Updated
4
Views
rithish
Posting Whiz in Training
268 posts since Apr 2011
Reputation Points: 23
Solved Threads: 9
Skill Endorsements: 0

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

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

deceptikon
Challenge Accepted
Administrator
3,428 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 56

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

sepp2k
Posting Whiz in Training
227 posts since Jul 2012
Reputation Points: 62
Solved Threads: 45
Skill Endorsements: 8

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.

Schol-R-LEA
Veteran Poster
1,022 posts since Oct 2010
Reputation Points: 414
Solved Threads: 163
Skill Endorsements: 10

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0713 seconds using 2.66MB