Thread: Help with for loop

  1. #1
    Programmer Frantic-'s Avatar
    Join Date
    Dec 2004
    Posts
    114

    Help with for loop

    im trying to make a little dos app that finds the factorial of the number the user enters.

    when i type in the number 7, i get 840, when i should be getting 5040.

    here is my source:
    Code:
    #include <iostream>
    using namespace std;
    int num;
    void calculate();
    void last();
    int main()
    {
    cout<<"Please enter the number you wish to find the factorial of: ";
    cin>> num;
    calculate();
    }
    void calculate ()
    {
             const int sent = num;
              for (int x = 1; x < sent - 1; x++){
                  num = num * x;
                  }
              last();
              }
    void last()
          {
              int input;
              cout<<"The answer is: " << num <<" \n";
              cin.get();
              cout<<"\n Would you like to enter another number?\n\n1.)Yes\n2.)No\n\nSelection:";
              cin>> input;
              switch (input){
              case 1:
                   cin.get();
                   main();
                   break;
              case 2:
                   cout<<"Thank you for using this program. Have a nice day.\n";
                   cin.get();
                   break;
                   }
                   }

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Check the logic of your loop condition:
    x < sent - 1
    This will terminate if x == sent - 1, and hence, that number will not get multiplied in.

    Cheers
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Code:
    x < sent - 1
    Change that to either of the following:

    Code:
    x <= sent - 1
    Code:
    x < sent

  4. #4
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Mwahaha! Beat you!
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  5. #5
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Adam Sandler said it best:

    You're gonna die, clown!

  6. #6
    Programmer Frantic-'s Avatar
    Join Date
    Dec 2004
    Posts
    114
    thanks guys.

    i had originally put that there, but changed it cause i thought it wouldnt work maybe i should have tested it 1st.

  7. #7
    C(++)(#)
    Join Date
    Jul 2004
    Posts
    309
    >>>maybe i should have tested it 1st.
    Always a good idea. I've done that several times and ended up spending two hours fixing something I had right the first time.
    To code is divine

Popular pages Recent additions subscribe to a feed