I'm brand spanking new to C++ so any help/suggestions would be great:
I'm suppose to be making a program that shows factorial for 1-5 using "for".
I have: for ( int n = 1; n <= 5; n++ ) but the output is killing me trying to figure out how I can manipulate 'n' to give me the factorial for each new integer.
I thought that I would do an if (n = 1) cout << 1 << endl;
and then else if for each integer after that with just the proper multiplication of each. However, when I run the program I just get an endless loop of 1. I assume this is because I am not returning back to the top to the 'for'. I don't know for sure though.
I'm being forced to use this method (for) to create the increments as I have already done it another way that works but isn't acceptable for a grade.
I appreciate the help.
#include <iostream>
using namespace std;
int main()
{
for ( int n = 1; n <= 5; n++ )
if (counter = 1)
cout << 1 << endl;
else if (n = 2)
cout << 1 * 2 << endl;
else if (n = 3)
cout << 1 * 2 * 3 << endl;
else if (n = 4)
cout << 1 * 2 * 3 *4 << endl;
else
cout << 1 * 2 * 3 * 4 * 5 << endl;
cout << "press enter to close\n";
cin.get();
return 0;
}
This works to give me a factorial of some number but it doesn't do it for all n up to a limit (which is what I need). The assignment is to have a program that spits out:
n! x
1 1
2 2
3 6
4 24
5 120
Maybe the misunderstanding comes from what I wrote for my program before since I'm likely using the if/else if wrong. I thought that the for would increment the digit once and output it to the if function and it would then make a decision what to do with it. Once the decision was made it would return to the for function to be incremented 1 more time until n=5.
Factorials start from 0. 0! is equal to 1.
If to use a recursive function as suggested by @bradw it could look the following way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
unsignedint factorial( unsignedint n = 5 )
{
int f = ( n == 0 ) ? 1 : n * factorial( n - 1 );
std::cout << n << ' ' << f << std::endl;
return ( f );
}
int main()
{
factorial();
return 0;
}
The factor *= fact; means that factor is now equal to the previous value of factor times the number fact.
It could also be written with an int called temp like this:
1 2 3
int temp;
temp =factor * fact;
factor=temp;
That would accomplish the same thing, but we're lazy, so we use the *= instead.
I got it now. So it is just storing the old number then multiplying by the new number. I never even thought of doing it this way, so much easier than trying to do if.
For my own understanding, why did my first set up not work? I should expect that I'll be writing a lot of else and if code later on this semester so I'd like to get a better grasp of it.