#include <iostream>
usingnamespace std;
constint arSize{5};
int main()
{
longlong factorials[arSize];
//sets array element 0 and element 1 to 1
factorials[1] = factorials[0] = 1LL;
//loops through 2 through array size of 20
for (int i = 2; i < arSize; i++)
{
factorials[i] = i * factorials[i - 1];
}
//displays loop iterations including 0! and 1!
for (int i = 0; i < arSize; i++)
cout << i << "! = " << factorials[i] << endl;
}
The array does not contain the numbers 1, 2, 3, ... as you might expect. It actually contains the factorials (as the name implies) so a single multiplication is enough to calculate the next factorial.
Let fx be factorial[x]:
1 2 3 4 5
f0 = 1 // definition
f1 = 1 // definition
f2 = 2 * f1 = 2 * 1 = 2 // first loop iteration
f3 = 3 * f2 = 3 * 2 = 6 // next iteration
f4 = 4 * f3 = 4 * 6 = 24 // and so on...