Wanted to add a bit more insight into the initial implementation (question).
-----------------------------------------------
In the first loop, you create a variable i.
This variable i has a specific memory address — let’s say it’s 0xabab.
During the first loop, i takes on the values 1 through 3, but its memory address doesn’t change.
Because of that, every element of test[i] ends up storing the same address (the address of i, 0xabab).
In the second loop, i is declared again in a different scope, so it gets a new memory address — it’s no longer 0xabab.
When you later print the values stored in test[i], you’re actually printing whatever is stored at the old address (0xabab), which still holds the value 3 (the last value from the first loop).
That’s why all elements print 3.