1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ Factorial Calculator

  1. Sep 12, 2011 #1
    1. The problem statement, all variables and given/known data

    Write a C++ code factorial.cc that calculates the factorial of an integer by direct multiplication. Start with your code in exercise (3), and modify it so that it gets "n" from the user and prints out n! = 1*2*3*...*(n-1)*n. To do this, use a "for" loop:

    Code (Text):
    int nfac;

    nfac = 1;
    for (int i = 0; i < n; i++)
      {
        ...
      }
    and within the curly braces set the variable nfac appropriately

    2. Relevant equations

    None.

    3. The attempt at a solution

    I am 100% lost on this problem. We don't have a text and we didn't learn about nfac or how to do these types of calculations in class so I don't really have anything to go off of.

    It says to start with my code from exercise 3 which is this. It works fine and I can mostly understand which lines do what.

    Code (Text):

    #include <iostream>

    using namespace std;
    int main(void)
    {
    int n;

     cout << "enter a number:";
     cin >> n;
     cout << "your number was " << n << "\n";

    return 0;
    }
     
    I don't have much past this. I've tried different combinations of things for last hour and a half but haven't gotten anything. Mainly because I zero idea where to put things. My latest guess was something like this.

    Code (Text):

    #include <iostream>

    using namespace std;
    int nfac;

    nfac = 1;
    for (int i = 0; i < n; i++)

    {
     cout << "enter a number:";
     cin >> n;
     cout << "your number was " << n << "\n";
    return 0;
    }
     

    I know this is completely incorrect and am almost embarrassed to even post it, but I really have nothing at all. I think the cout line needs something that actually points it to what the factorial is?

    As you can see it looks like I just slapped his hint in there and called it good, but I've tried everything and this is the closest/cleanest attempt I've gotten so far - even though it is wrong.
     
  2. jcsd
  3. Sep 12, 2011 #2

    Mark44

    Staff: Mentor

    nfac isn't something that you would have learned about - it's just the name of a variable.

    Do you know how to calculate the factorial of a number? For example, can you calculate 10!
     
  4. Sep 12, 2011 #3
    Yes, I can calculate that as long as it's on paper or a calculator...i.e. not through c++ :tongue:

    Also after some more thought, I think I might be onto something.

    Perhaps I need to use my solution to part (3) as I posted along with his hint, but rather than combining them into one sub routine, I need them as separate.

    So I'd leave my solution to (3) alone except for the last cout where it returns the solution. Then under that as a new sub routine I can define how the nfac works and reference the calculation into the cout of my (3).

    Am I on the right track?

    I would need come up with the line for finding the factorial. Which is what I believe you are hinting at.
     
  5. Sep 12, 2011 #4

    jhae2.718

    User Avatar
    Gold Member

    You could create a function for the factorial, but you can do it in one statement in a for loop.

    Some things to think about:
    1. How is the factorial defined? (Think recursion...)
    2. What does a for loop do?
    3. How can you combine the two?

    For you last example code, remember that a C++ file must* have a main function, e.g.
    Code (Text):

    #include <iostream>
    // plus any other libraries

    using namespace std;

    int main(void) // void if no inputs
    {
        //do stuff
    }
     
    *Assuming it's not an include file like iostream, cmath, etc.
     
  6. Sep 12, 2011 #5
    On these kind of problems it's often helpful to write an algorithm in plain English, after this step is done the rest should be almost trivial.
     
  7. Sep 12, 2011 #6
    I am not familiar with the word subroutine, but I can sense you are going in the right direction. I would move this part of the code outside the for loop:

    cout << "enter a number:";
    cin >> n;

    Since you have put this in the for-loop, it is going to repeat through the program n number of times. Put this before the for-loop. So now for what goes inside the for-loop. So you know how to figure out factorials in paper but it is the same in C++. Remember n! = 1*2*3*...*(n-1)*n. So once our user types in the value n you would know the limit of the for loop. You would need to multiply all the numbers up to the number n. That is what the for loop is for. Use the value of i to multiply to each value of what you get for n. Think of something like n = n+i. But instead of adding you would be multiplying. Hope this helps you.

    Also don't forget the return 0; at the end of your main.
     
  8. Sep 13, 2011 #7
    I guess sub routine isn't the right word. I hesitated calling it that, but didn't know anything else to use. I meant each separate section of my code. So the int main is one and int nfac would be the other.

    Code (Text):

    #include <iostream>

    using namespace std;
    int main(void)
    {
    int n;

     cout << "enter a number to be factorialized:";
     cin >> n;
     cout << "The factorial of "<< n << " is "<< nfac << endl; //I need to reference my factorial calculation here somehow??

    return 0;
    }

    int nfac;

    nfac = 1;
    for(int i = 0; i < n; i++)
      {
       nfac = nfac*i
      }
     
    I know to calculate the factorial I'd have something like Ivan92 said; n! = 1*2*3*...*(n-1)*n, but I am not sure how that translates to C++? I assume it goes in with the nfac part like I mentioned above.

    In the first part I have a \n. We didn't learn what that did, just to type it in and try the code. Does that cause the original script to actually display the number in that problem?

    Like I mentioned we didn't really learn much. Just about the entire lesson has been pasted in here. So you can see I don't have a lot to start with.

    Thanks everyone for the help so far.
     
    Last edited: Sep 13, 2011
  9. Sep 13, 2011 #8
    When I try to compile it, it get this error.

    Code (Text):

    factorial.cc:17: error: expected constructor, destructor, or type conversion before '=' token
    factorial.cc:18: error: expected unqualified-id before 'for'
    factorial.cc:18: error: expected constructor, destructor, or type conversion before '<' token
    factorial.cc:18: error: expected constructor, destructor, or type conversion before '++' token
     
    Do I need to define i somehow? It looks like all of my errors start before the i.
     
  10. Sep 13, 2011 #9

    Mark44

    Staff: Mentor

    All of your code starting with the line int nfac; should be moved so that it is inside the body of your main() function.

    This is good advice from estro. Let's start with that, and not worry about writing C++ code until you understand the algorithm you're going to use.
     
  11. Sep 13, 2011 #10
    Note that everything should be inside of the main function (unless otherwise told). So the last part after the 3rd to last bracket should be in main. Also I would have the cout result after the for loop. Also your cout should have the n instead of nfac.

    Also I see you are using two int data types when you really only need one. So you don't need "int nfac; nfac = 1;" part. In the for loop, replace nfac with int n. After that, it should be working but I have not tested it myself.
     
  12. Sep 13, 2011 #11
    I gave that a try and it reduced my errors down to two.

    I'm using this now.

    Code (Text):

    #include <iostream>

    using namespace std;
    int main(void)
    {
    int n;

     cout << "enter a number to be factorialized:";
     cin >> n;
     cout << "The factorial of "<< n << " is "<< "\n" << endl;

    int nfac;
    for(int i = 0; i < n; i++)
     
       int n = nfac*i;

    return 0;
    }

     
    It compiles nicely with no errors - so we are getting close. However, my "answer" displays as "the factorial of 4 is " but nothing after is. The \n has to be there so maybe my calculation is wrong and isn't finding the factorial?


    Good idea. So I just did this in my head rather than writing it first. But here is what I was thinking before I started. Hopefully this is what you guys mean.

    I need to be able to enter a number and find its factorial

    Enter original number after terminal asks for number at prompt

    Factorial is then calculated by 1*2*3*...*(n-1)*n

    Factorial is displayed on terminal.
     
  13. Sep 13, 2011 #12
    I believe it is because the cout line needs to go after the for loop. I see what you are doing now. So replace the n in the for loop with nfac again (I know I told you to replace it with n. Sorry :embarrassed:) So it should look like this.

    "int nfac=1;
    for(int i = 0; i < n; i++)

    { int nfac = nfac*i;}

    return 0;"

    I added the = 1 part (just to be safe and make sure it doesn't have the default value of zero). I also added in those brackets. Its a good thing to have. Now after your for loop you should put your cout statement. The reason it is not displaying is because you are couting a new line. It should look something like this:

    cout << "The factorial of "<< n << " is "<< nfac << endl;

    You would be displaying what is the variable nfac instead of a new line.
     
  14. Sep 13, 2011 #13
    Okay here is what I have now.

    Code (Text):

    #include <iostream>

    using namespace std;
    int main(void)
    {
      int n;

      cout << "Enter a number to be factorialized:";
      cin >> n;


      int nfac=1;
      for(int i = 0; i < n; i++)

        { int nfac = nfac*i;}

      cout << "The factorial of "<< n << " is " << nfac << endl;

      return 0;
    }
     
    If I run it like that I will always get an answer of 1.
    I tried removing the 1 so I had int nfac; and got an answer of -4199132 no matter which number I entered.
     
  15. Sep 13, 2011 #14

    uart

    User Avatar
    Science Advisor

    Only declare each variable once. Don't re-declare it in every iteration of the loop!
     
  16. Sep 13, 2011 #15

    uart

    User Avatar
    Science Advisor

    Also double check your loop counter start and end values. Are you sure you want to multiply by zero?

     
  17. Sep 13, 2011 #16
    If I get rid of that line, it doesn't work. Hmm...

    Maybe that's my problem? Although that line was given in the lab, so I assumed that had to be there?
     
  18. Sep 13, 2011 #17
    Code (Text):
    import java.util.Scanner;

    public class Snippet {
        public static void main(String args[]) {
        int n,nfact;
        while(true){
    Scanner in=new Scanner(System.in);
    System.out.println("Enter n");
    n=in.nextInt();
        nfact=1;
        [B][COLOR="DarkRed"][COLOR="Red"]for(int i=2;i<n+1;i++)
        {
        nfact=nfact*i;
        }
        [/COLOR][/COLOR][/B]System.out.println(" Factorial of " + n + "  is  " +nfact);
       
    }
        }
       
    }
     
    This is the java version, please observe for loop !
     
  19. Sep 13, 2011 #18
    Ooooooooh!

    After looking at yours and uart's tips:

    (and the mult. by zero comment)

    I took off my second int fact changed my loop values and voila...

    Code (Text):



    #include <iostream>

    using namespace std;
    int main(void)
    {
      int n;

      cout << "Enter a number to be factorialized:";
      cin >> n;

      int nfac=1;
      for(int i=2; i < n+1; i++)

        { nfac = nfac*i; }

      cout << "The factorial of "<< n << " is " << nfac << endl;

      return 0;
    }
     
    Finally works!

    Now to study why I made the mistakes.

    Thanks again for the help everyone!
     
  20. Sep 13, 2011 #19
    On a side note; is there a way to get this to work?

    for (int i = 0; i < n; i++)

    Once I found my extra int, it would always = 0. Because that loop is multiplying by zero? That line is directly from the lab, so I wonder if it is supposed to work?
     
  21. Sep 13, 2011 #20
    Precisely! It starts from zero and multiplying zero will always get you zero. Sometimes professor will make a mistake.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook