so hypothetically, if the i loop itself is nested within another outer loop and if the i loop fails its condition and break out of its loop. then the i = 0 again? same as the j loop inside the i loop
So the issue is still how we can have 6 zeroes in the subarrays…
Use the tool to examine this code, and look at what happen to the row variable and the newArray variable
That’s the reason why you need row = [] in the loop, to avoid this
function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
console.log('i = ' + i);
console.log('row starts as ' + JSON.stringify(row));
// Adds the m-th row into newArray
for (let j = 0; j < n; j++) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
console.log('after pushing values to row, row is ' + JSON.stringify(row));
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
Have you ever tried repl.it multiplayer functionality? If you are up to it and like this is not easy no explain things, we can try if having the same piece of code in front Help with explaining and understanding
dont worry i used the tool already and i analysed all 44 steps completely. the row = [] is to reassign itself everytime we push 2 zeroes into the empty newArray how? j= 0 and j=1.
and if we want the other 4 zeroes, we gotta get j =2 to fail the condition to get back to “j=0” again. so it could push the rest of the zeroes successfully. of course we have to iterate back up to the i loop condition everything again.
the pythontutor tool really helped me well. i found out that the i or j increments ONLY when we reach the very end of their own loop. like if i++ ONLY when we finish executing its statements and then iterating the j loop twice, pushing the zeroes, increment j and failing its condition then go back up to the i condition to increment i
no don’t really know what that is honestly xd