Recursion Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bpurificacion
    New Member
    • Mar 2008
    • 9

    Recursion Problem

    Hi i'm currently trying to do a recursion homework assignment that does the factorial of any number the user inputs. I'm having trouble with getting the number the user inputs, and putting it in the function. Any suggestions?

    #include <iostream>
    using namespace std;

    int fact(int n);

    int main()
    {
    char ch;
    int choice;

    do
    {
    cout << "Pick any positive integer: " << fact(choice);
    cin >> choice;


    cout << "Press 'y' to run again, any other key to quit:";
    cin.ignore();
    cin.get(ch);
    } while (ch =='y' || ch =='Y');

    return 0;
    }

    int fact(int n)
    {
    int answer;

    if (n==1)
    return 1;
    else
    answer = fact(n-1) * n;
    return answer;
    }

    this is what i have so far. and it says i have an "uninitiali zed local variable 'choice' used" in the bolded area.
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Right. Your current setup displays "Pick any positive integer." and then calculates the factorial of a number the user hasn't displayed yet! Move fact(choice) to a cout statement that's after the user has input the value and this will work fine.

    Comment

    • bpurificacion
      New Member
      • Mar 2008
      • 9

      #3
      Thanks! that fixed the problem. I couldn't even do that for something so easy and so simple. thats a beginner for you...

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Not that it matters much but change your if statement:

        [code=c]
        if (n == 1)
        [/code]

        to this:

        [code=c]
        if (n < 1)
        [/code]

        because those stupid users like to input silly negative numbers and you don't
        want your stack to overflow.

        kind regards,

        Jos

        Comment

        Working...