Can someone walk me through the following code:
function square(n) {
let result = 0;
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
return result;
}
//
example:
console.log(square(5)) // 25
How does this for loop work in creating a square of an n number? I don't know where to start in approaching how this works.
The square of a number can be visualized as the number of squares in a grid. 5x5, for example, is 5 wide by 5 tall:
You can think of the nested loop in your code
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
emulating movement along the grid.
When i is 1, it's going along the first row. When j is 1, that corresponds to the first column. That corresponds to the first square. Next iteration corresponds to the first row, second column - etc, until i <= n is no longer fulfilled, at the end of the row. The next row then iterates n times, and so on.
You'll see that the number of total iterations (where result += 1 runs) is equivalent to n * n, as the nested loop implements.
In short, the inner(j) loop runs 5 times for every iteration of the outer(i) loop..
Basically,
for each i = 1, j runs 5 times
for i = 2, j runs 5 times //total 10 times
for i = 3, j runs 5 times //total 15 times
for i = 4, j runs 5 times //total 20 times
for i = 5, j runs 5 times //total 25 times
So the result gets incremented 25 times, and hence the answer is 25