HI @mayanwiner !
Welcome to the forum!
As mentioned earlier, product does not just stay at one .
It is constantly being updated.
I am going to copy and paste a reply I made to another user on how this works and hopefully it will help you too.
So let’s focus on this nested array.
[[1,2],[3,4],[5,6,7]]
Our task is to get the product of all of the numbers in the subarrays.
These are the sub arrays
[1,2]
[3,4]
[5,6,7]
When i=0
this piece of code arr[i]
targets the first sub array [1,2]
.
We check the condition
Is i < arr.length;
Yes
Now we enter the inner loop(or the j loop) and have this code arr[i][j]
That translates to arr[0][0]
or the number 1.
That second [0]
targets the first element of the subarray because remember arrays are zero based index.
So now we can execute this line of code
product = product * arr[i][j];
translates to
1 = 1*1
Now we increment j by 1 ( j++)
And product is still 1.
We check the condition
Is j < arr[0].length;
Yes
Now arr[i][j]
turns into arr[0][1]
arr[0][1]
is the second element in our first subarray.
The second element is the number 2.
Now we execute this line of code
product = product * arr[i][j];
translates to
2 = 1 * 2;
Now product is 2.
We now have to increment j by 1 ( j++)
Now j =2
Now we check the condition of the j loop
Is j < arr[0].length
?
No, because 2 is not less than 2. This subarray [1,2]
only has two elements.
Now we leave the j loop and increment i
by 1 (i++)
Now i=1
We check the condition
Is i < arr.length;
Yes
Now arr[i][j]
is arr[1][0]
Then we go through the same steps as before and always assigning the new result to the product.
Hope that makes sense on how nested arrays work.