I have managed to write a simple program to display the factorials of each number up to 12, however I'm having trouble explaining each part of the code as it has took me lots of trial and error to get it to work. Any help is appreciated no matter how brief.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main() //main function
{
unsignedlongint a, b, c;
for (a=1;a<=12;a++)
{
b=1;
for (c=1;c<=a;c++)
b=b*c;
cout << "The factorial of " << a << " is - " << b << endl;
}
system("pause");
return 0;
}
[edit] Disregard; I read "Fibonacci" when OP said "Factorial". Oops!
The program is not correct. Factorial is 1, 1, 2, 3, 5, 8, 13, ...
Commentary helps you explain to yourself what you are doing. If the only commentary you have is "trial and error and seems to work", I've learned (from much experience) that it is an indication that the program is probably wrong.
To compute the factorial, you need three values: the current value (being computed) and the two values that came before that.
For example:
1 2 3
int a = 1;
int b = 1;
int c = a + b;
Once you get the current value, you can forget the smallest value:
1 2
a = b;
b = c;
And you can compute the next value:
c = a + b;
You only have to do that N-2 times. (Do you know why you don't have to do it for N=1 or N=2?)
1,1,2,3,5,8 . . . is fibonacci series, not factorial!
Factorial is n * (n-1) * (n - 2) . . . * (1)
As to comments; Like ne555 said, Start by breaking the description of what you need to do into sentences:
1. For each integer from 1 to 12
2. Determine the factorial of the integer where factorial = count!
3. Display the count and the factorial of the count