Link Search Menu Expand Document

Modulo to the Rescue

In the previous example, you need a way to keep looping over the list items, so when i gets to 9, it will go back around and get the “0th” item from the list again. This is where the modulo operator % can help you out.

Look at the code below: run it somewhere in your act() method and see if you can figure out what is going on. You shoud get 0 to begin with.

System.out.println(18 % 6);

Try changing the numbers in the print command. There are some examples to try below:

System.out.println(17 % 6);
System.out.println(12 % 6);
System.out.println(13 % 6);
System.out.println(6 % 6);
System.out.println(0 % 6);
System.out.println(1 % 6);
System.out.println(8 % 6);
System.out.println(11 % 6);

Did you figure it out? The % operator prints out the remainder of a division. For example, 15 ÷ 6 is 2 with a remainder of 3. Therefore 15 % 6 would be 3. We can use this operator to help with the problem of running off the end of the list. If the for loop iterations go beyond the length of the list, you can just do a % of the length of the list.

Have a look at the example below, and read through the code carefully to make sure you can see how the modulo operator is used. Try this for your for loop in the act() method.

for (int i = 0; i < 40; i++)
{
    setColor(colors[i % colors.length][0], colors[i % colors.length][1], colors[i % colors.length][2]);
    moveAndDraw(i);
    turn(98);
}