Need help with pointers

Hello,

I am kind of new to pointers variables and dynamic memory allocation
so please can someone explain when the following code is outputting the following result

1
2
3
4
5
6
7
8
9
10
11
 double a[10];

	a[0] = 1;
	for (unsigned i = 1; i < 10; i++)
		a[i] = a[i - 1] * i;

	p = &a[0];  // p = a;
	
	for (unsigned i = 0; i < 10; i++)
		cout << "  " << p[i];
	cout << endl;


and the output is

1 1 2 6 24 120 720 5040 40320 362880
p = &a[0]; // p = a;
Here you make p point to first element of the a array. Starting for this moment p is almost undistinguishable from a, and you can use p as you could use a (with some exceptions)

So line 10 is equivalent to cout << " " << a[i];
I was doing the program on a paper and I am not getting the same output I get 1 1 2 6 then 12 20
Program output looks correct:
...
6!=720
7!=5040
8!=40320
9!=362880
ohhh, I didn't notice that there is factorial involved in this

so I was thinking little bit about this and the factorial part was a bit of confusing

but then I figured out that the second FOR loop is sending the numbers to first FOR loop to do the factorial thing ? Right

this my first time seeing factorial implementation
Last edited on
Registered users can post here. Sign in or register to post.