FSEM 131
Lab 2 |
Repetition
|
To review the lecture material download the posted code and the references pages on while loop.
1. [2 pts] Consider the following program that uses a while
loop to print increasing numbers on the console.
println("counting up with a while loop"); int MAX = 5; // constant declaration used to terminate the loop int i = 1; // initialization of counter variable // i is the loop variable, incremented each time through the loop while (i <= MAX) { // continutation test: boolean expression // tested before continuing next iteration // print the counter followed by a space (no new line) print(i + " "); //counter i is updated i = i+1; } // change line with println println(""); println("done: out of the while loop"); println("---------------------------");
The synthax for a while
loop is
the following
initialization while (continuation test) { statements one statement updates the variable tested in the contintation test }Now that you understand the process of a
while
loop, copy
the above code into a Processing program called loops
and do the following.
- Run the program and examine its output on the console.
- Change one line of the program to print from 1 to 10.
- Declare and use a variable to print starting at 3 for a second
while
loops. - Add the
while
loop below the provided code, such that
this new loop counts down from 12 to 0.
loops
should be the following
counting up with a while loop 3 4 5 6 7 8 9 10 done: out of the while loop --------------------------- counting down with a while loop 12 11 10 9 8 7 6 5 4 3 2 1 0 done: out of the while loop
2. [4 pts] Using a while
, write a program moreLoops
that produces on the console the output below for Loop 1 and Loop 2.
You should write down your thought process first on a piece of paper.
Check manually the loop iterations before pressing the run bitton. Pay attention to
bounds (where the repetition starts and ends).
Loop 1 0 3 6 9 12 15 18 Loop 2 20 15 10 5 0
2. [4 pts] Write a program ellipseLoop.pde
that creates an output similar to the image below.
- The application window is 260 X 260 pixels.
- The background is white.
- The circles are centered in the window.
- The smaller circle is 40 by 40.
- The circles are separated by 20 pixels.
3. [4 pts] Write a program called dice
that creates
a 300 x 300
window and initializes the variables
int dotSize = 25; int dotX = 40; int dotY = 40; int incX = 50; int incY = 50;
which are used in a loop to produce the image below.
Changing the window size to 400 x 400
produces
this image.
4. [4 pts] Write a program manyLinesGrid.pde
that uses a for loop
to create an output similar to the image below.
- The application window is 200 pixels wide and 200 pixels high.
- The lines are separated by 10 pixels in each direction: horizontal and vertical.
- The padding (space around the grid) is 20 pixels on all the sides.