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.
using namespace std;
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;
cout << 1 * 2 * 3 * 4 * 5 << endl;
cout << "press enter to close\n";
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:
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
unsignedint factorial( unsignedint n = 5 )
int f = ( n == 0 ) ? 1 : n * factorial( n - 1 );
std::cout << n << ' ' << f << std::endl;
return ( f );