Modulus (%) Illustrated

Here is a little demonstration that might help to understand the sometimes mysterious modulus function (aka remainder), denoted by the % operator in Javascript and many programming languages.

In brief, when we write d % n, it means compute the remainder of d divided by n.

It may not be obvious, but this gives remainder a wrap-around property. If d is counting 0, 1, 2, 3, …, then d % n, computes the repeating sequence 0, 1, 2, … n-1, 0, 1, 2, … n-1, etc.

If you move the mouse up and down, you can see d % n for different values of n.

modulus_illustration

var count = 0;     // counts from 0 to infinity
var fr = 4;        // frame rate
var margin = 20    // left and top margin size
var spacing = 50;  // spacing between boxes

function setup() {
    createCanvas(500, 500);
    frameRate(fr);
}

function draw() {
    background(220);
    // show only one row at a time based on mouseY:
    var row = int((mouseY - margin + 10) / spacing);
    // make sure row is on the canvas:
    row = constrain(row, 0, 8);
    var m = row + 2;          // the modulus
    var i = count % m;
    var x = margin + 40 * i;  // x, y coordinates of the box
    var y = margin + 50 * row;
    rect(x, y, 40, 40);
    textSize(20);
    text("" + i, x + 10, y + 25); // show i in the box

    // display additional info at upper right:
    text("Move the mouse to change the modulus.",
         width - 380, 40);
    text("modulus = " + m, width - 150, 70);
    text("count = " + count, width - 150, 100);
    text("count % " + m + "= " + i, width - 150, 130);

    // buttons to speed up / slow down frame rate:
    rect(width - 200, 150, 80, 30);
    text("Slower", width - 195, 170);
    rect(width - 110, 150, 80, 30);
    text("Faster", width - 105, 170);
    text("Frame Rate = " + fr, width - 180, 210);
    
    // frame count (could have used frameCount instead)
    count = count + 1;
}


// test if mouse is in a button defined by x, y, w, h:
function mouseIn(x, y, w, h) {
    return mouseX > x & mouseX < x + w &&
           mouseY > y && mouseY < y + h;
}


// if mouse presses a button, speed up or slow down:
function mousePressed() {
    if (mouseIn(width - 200, 150, 80, 30)) {
        fr = fr * 0.8; // lower frame rate
    } else if (mouseIn(width - 110, 150, 80, 30)) {
        // Increase frame rate. The +1 is a hack so
        // that even with low frame rates and truncation,
        // fr will increase:
        fr = (fr + 1) / 0.8; 
    }
    // Minimum rate is 1, rate is an integer for prettier display
    fr = max(1, int(fr)); 
    frameRate(fr);
}