For loop iteration through an array (factorial)

Can anyone help me to understand how factorials[i] = i * factorials[i - 1]; for factorials[4] gets 24 and not 12.

Granted, the program works how it should, but I am miffed why I cannot figure this out. Any guidance for this beginner would be most appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
const int arSize{5};

int main()
{
	long long 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;
}
Last edited on
closed account (48bpfSEw)
4! = 1*2*3*4 = 24

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

Zhuge - Thank You!

Topic archived. No new replies allowed.