Search code examples
javascriptfor-loopnested-loopsprocessing.js

Nested for loop not working


I have this code

var draw = function() {
var bx = 0;
var by = 0;
//height
for (var i = 0; i < 11; i++) {
    //width
    for (var s = 0; s < 10; s++) { 
        block(bx,by,air);
        bx = bx + 50;
    }
    by = by + 50;
} 

What is happening is when I run draw() it should draw squares in the entire portion of a 10 by 10 plot. However, this is not the case. It is all messed up and I don't know what is happening.

NOTE: this is using processing.js. You can find the complete code here: https://www.khanacademy.org/computer-programming/mc-10/4727460304912384


Solution

  • Don't use separate variables for the iteration and plotting.

    var width = 50;
    for (var by = 0; by < 11 * width; by += width) {
        for (var bx = 0; bx < 10 * width; bx += width) {
            block(bx, by, air);
        }
    }
    

    or:

    var width = 50;
    for (var i = 0; i < 11; i++) {
        for (var s = 0; s < 10; s++) { 
            block(s * width, i * width, air);
        }
    }