Link Search Menu Expand Document

Enormous Lists

You can now have a go at creating a list of colours that’s a little longer than before. To do this you can use a while loop. Unlike a for loop, a while loop keeps running until a specific condition has been met.

Look at the code below. The while loop is used to gradually increase the value of g until it reaches 255. Each time, the colours are added to the list.

int r = 255;
int g = 0;
int b = 0;

// When creating an array, we have to allocate its size.
// 256 is the number of colors added with the loop below.
// 3 allows for r, g, and b to be stored.
int[][] colors = new int[256][3];

// Color Index
int c = 0;

while (g < 256)
{
    colors[c][0] = r;
    colors[c][1] = g;
    colors[c][2] = b;
    g += 1;
    c += 1;
}

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

Result:

spiral

Can you add in two more while loops to add more colours? The next loop should gradually decrease r until it reaches 0. The final one should then increase b until it reaches 255. Good luck!