In this step, we will implement the code examples 4.5 and 4.6 from your lectures. We will also do an exercise with a nested while loop.
Create a new Processing sketch and call it Example_4_5.
Enter the following code into your sketch:
int yCoordinate = 60;
size(600, 300);
background(102);
fill(255);
noStroke();
int i = 0;
while (i < 4)
{
rect(50, yCoordinate, 500, 10);
yCoordinate = yCoordinate + 20;
i++;
}
Run your code. This code should draw four white horizontal blocks as shown below:
Save your sketch.
In the above sketch, do a Save as… and give it the name Example_4_6.
Make the necessary changes to remove the yCoordinate variable and update the while loop accordingly:
size(600, 300);
background(102);
fill(255);
noStroke();
int i = 60;
while(i <= 120)
{
rect(50, i, 500, 10);
i += 20;
}
Run it and check that the same output as above is produced.
Save your sketch.
Create a new Processing sketch in your workspace and call it lab04_step02.
Enter the following code into your sketchbook:
int i = 0;
while ( i < 4 ) {
int j = 0;
while (j < 4 ) {
println("The value of i is: " + i + " and j is: " + j);
j++;
}
i++;
}
Run your code. This code should print out this series of lines to your console:
Look at these lines, in particular, look at the values printed for i and for j. Do you understand the mechanics of how the nested while loop works?
Save your sketch.