# Homework Help: C++ Factorial Calculator

1. Sep 12, 2011

### erok81

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. Sep 12, 2011

### 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!

3. Sep 12, 2011

### erok81

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.

4. Sep 12, 2011

### jhae2.718

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

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.

5. Sep 12, 2011

### estro

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.

6. Sep 12, 2011

### Ivan92

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.

7. Sep 13, 2011

### erok81

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
8. Sep 13, 2011

### erok81

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.

9. Sep 13, 2011

### 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.

10. Sep 13, 2011

### Ivan92

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.

11. Sep 13, 2011

### erok81

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.

12. Sep 13, 2011

### Ivan92

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.

13. Sep 13, 2011

### erok81

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.

14. Sep 13, 2011

### uart

Only declare each variable once. Don't re-declare it in every iteration of the loop!

15. Sep 13, 2011

### uart

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

16. Sep 13, 2011

### erok81

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?

17. Sep 13, 2011

### stallionx

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 !

18. Sep 13, 2011

### erok81

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!

19. Sep 13, 2011

### erok81

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?

20. Sep 13, 2011

### Ivan92

Precisely! It starts from zero and multiplying zero will always get you zero. Sometimes professor will make a mistake.

21. Sep 13, 2011

### stallionx

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;
for (int i = 0; i < n; i++)

{
nfact=nfact*(i+1);
}

System.out.println(" Factorial of " + n + "  is  " +nfact);

}
}

}

22. Sep 13, 2011

### Staff: Mentor

stallionx,
Your formatting makes this simple code very difficult to read. Here is my effort to improve the readability.

23. Sep 14, 2011

### erok81

I know this is a different problem, but I'm still stuck on the same concepts (this one isn't an assigned problem, but I think it will go a long in helping me understand these).

I am confused when to use brackets and a couple of other things.

Here is my original problem.

Code (Text):

// this code is supposed to print out a list of sin(i)/i for i=0,1,2...,10.
// it is broken....

#include <iostream>

using namespace std;

int main()
{
int x;

cout << " here is a list of sin(i)/i versus i: " << endl;
for (i = 1; i <= 10; i++)
cout << " sin(" << i << ")/i is ";

if (i = 0) {
// special case of i=zero. The correct limit as sin(x)/x as x->0 is 1.
cout << "1\n";
} else {
x = sin(i)/i
cout << x << endl;
}

I modified it to this in an attempt to fix it.

Code (Text):

// this code is supposed to print out a list of sin(i)/i for i=0,1,2...,10.
// it is broken....

#include <iostream>
#include <cmath>

using namespace std;

int main(void)
{
int i;

cout << " here is a list of sin(i)/i versus i: " << endl;
for (i = 1; i <= 10; i++);
cout << " sin(" << i << ")/i is ";

if (i = 0);

// special case of i=zero. The correct limit as sin(x)/x as x->0 is 1.
cout << "1\n"<<;
}
else
{
x = sin(i)/i;
cout << x << endl;
return;
}

I think I might have made it worse though. So let me start off by saying when is is appropriate to use the brackets?

Any other tips or hints to fix this thing?

24. Sep 14, 2011

### Staff: Mentor

I doubt that this will compile. Here are some problems I see.
1) There is code that isn't in the body of any function (all of the code from else on).
2) Your for loop is not doing anything useful. This is because the body of the for loop is null.
The statement for(i = 1; i <= 10; i++);
causes the loop control variable, i, to be set respectively to 1, 2, 3, ..., 10, and finally 11, which is the first value that is too large. At each step, nothing useful happens.

You should get in the habit of using braces - {} - to surround the body of for loops, while loops, if statements, else statements, and other control statements.

Here is a typical for loop.
Code (Text):
for (i = 0; i < 10; i++)
{
// Body of for loop
}
If the body of a for loop etc. consists of a single statement, you don't have to use braces, but I would STRONGLY recommend using them. Many people have been burned by not using braces, and then coming back to decide they need another statement in the body. If the loop body is surrounded by braces, no problem, but if not, only the first statement is considered by the compiler to be the loop body, even if your indentation suggests otherwise.

Here is a typical if - else statement
Code (Text):
if (i == 1)
{
// What's supposed to happen if i equals 1
}
else
{
// What's supposed to happen if i is NOT equal to 1
}

3) if (i = 0);
There are at least two things wrong here.
a) You are using the assignment operator =, instead of the equals operator ==.
b) Using the assignment operator instead of the equals operator causes the value 0 to be stored in the location for i. The value of this assignment expression is 0, which is considered false in C and C++. (Anything nonzero is considered to be true.) As a result of the value of the expression being false, the null statement following the right parenthesis is not executed.
In short the statement if (i = 0); does exactly nothing.

4) You are not understanding that the computer executes your code sequentially line after line (unless you have a loop or branch structure - e.g., if - else). If you want to print
sin(1)/1 is <something>
sin(2)/2 is <something>
.
.
.
you are going to have to compute sin(1)/1, sin(2)/2, etc. BEFORE the print statement is finished executing.

This would do what you want:
Code (Text):

for (i = 1; i <= 10; i++)
{
cout << " sin(" << i << ")/i is " << sin(i)/i << endl;
}

There is no need for a special case for i == 0; the loop runs from i == 1 through i == 10 and then quits.

25. Sep 14, 2011

### erok81

Oh wow! Thank you for that detailed post. I'm pretty sure I just learned more from that post than I have over the week of classes. Now I think I get how this stuff is used.

While I am working through it all, I've got two last questions to clear up.

Brackets. Do I need to finally close it all?

Say I've got my original bracket after the int main() and then numerous open/closed brackets for my loops etc. Do I then need to have a closing one after everything to end my int main, or is that taken care of in the first set of functions (or whatever you want to call them).

My return 0; where does that go? I'm not fully understanding what it does. I've seen some examples where they have something other than 0.

Thanks again for taking the time to write all of that up!