Tuesday, 7 April 2009

Chunk 13 - FINISHED!

Yay, I finished chunk 13. Just got to to send it in now
And then I need to finish chunk 82!

Chunk 13 2nd Program

Finally finished the 2nd program for chunk 13 - PirateShipArmada - hehe
Code and screenshot below






/**
*
* Example of while statements for chunk 13

* Displays a number of pirate ships that move across the screen at different
* speeds
*
* @author Antony Lees
*/

// wave directions
int UP = 1;
int DOWN = -1;

// pirate ship variables
PirateShip[] ships;
int waveHeight;
int waveDirection;
int shipCount;


void setup() {
// set the size of the window
size(600, 400);

// initialise the variables
shipCount = 10;
waveHeight = 20;
waveDirection = UP;

// create the array of ships using a for statement (section 12)
ships = new PirateShip[shipCount];
for (int i = 0; i < ships.length; i++) {
ships[i] = new PirateShip();
}
// smooth pixels
smooth();
}

void draw() {
// determine of the vwaes should be going up or down
// using a conditional statement (section 10)
if (waveHeight <= 5) {
waveDirection = UP;
}

if (waveHeight >= 20) {
waveDirection = DOWN;
}
// light blue background
background(102, 205, 170);

// waves
noFill();
// wave y coordinate
int waveY = 10;
// while the y coordinate is less than the height of the window
while (waveY <= height) {
// wave x coordinate
int waveX = 0;
// while the x coordinate is less than the width of the window
while(waveX <= width) {
// draw a semi=circle arc
arc(waveX, waveY, 20, waveHeight, 0, PI);
// increase the x coordinate by 20
waveX += 20;
}
// increase the y coordinate by 20
waveY += 20;
}

// move and draw ships while there are more ships to do
int currentShip = 0;
while (currentShip < ships.length) {
ships[currentShip].move();
ships[currentShip].display();
currentShip++;
}
// change the wave height for next time
waveHeight += waveDirection;

}

/**
* Pirate ship
*
* @author Antony Lees
*/
class PirateShip {
// pirate ship variables
float xPosition;
float yPosition;
float speed;
float shipLength;
int sails;
int sailColour;
int[] availableSailColours;
int portholeCount;
float sailSpacing;

/**
* Creates a new pirate ship
*/
PirateShip() {

// set up the sail colours - done like this for processing.js support
availableSailColours = new int[4];
availableSailColours[0] = color(0, 0, 0);
availableSailColours[0] = color(255, 36, 0);
availableSailColours[0] = color(255, 255, 0);
availableSailColours[0] = color(235, 235, 235);
// initialise the ship
initialise();
}

/**
* Initialise the ship
*/
void initialise() {
// initialise the ship at a random-ish location
xPosition = random(600, 700);
yPosition = random(50, 350);
shipLength = random(40, 100);
// determine the speed and number of sails based on the length
speed = shipLength / 20;
sails = min(((int) shipLength / 30), 3);
// select a sail colour from the list
sailColour = availableSailColours[(int) random(0, availableSailColours.length)];
portholeCount = (int) shipLength/12;
sailSpacing = floor(shipLength / 3);
}

/**
* Move the ship by the speed number
*/
void move() {
xPosition -= speed;
}

/**
* Do all the work of displaying the ship
*/
void display() {
// calculate ship coordinates
float frontOfShipXPosition = xPosition - (shipLength / 2);
float backOfShipXPosition = xPosition + shipLength + (shipLength / 3);

// ship hull
// brown lines and fill
stroke(139, 71, 38);
fill(139, 71, 38);
// middle rectangle
rect(xPosition, yPosition, shipLength, 20);
// front and back
triangle(frontOfShipXPosition, yPosition, xPosition, yPosition, xPosition, yPosition + 20);
triangle(xPosition + shipLength, yPosition, backOfShipXPosition, yPosition, xPosition + shipLength, yPosition + 20);

// draw the sails
float initialSailXPosition = xPosition + 15;
// black lines
stroke(0);
for (int i = 0; i < sails; i++) {
// sail
fill(sailColour);
quad(initialSailXPosition + (sailSpacing * i), yPosition - 40, initialSailXPosition + (sailSpacing * i) + 10, yPosition - 40, initialSailXPosition + (sailSpacing * i) + 20, yPosition - 10, initialSailXPosition + (sailSpacing * i), yPosition - 10);
// mast
fill(0);
line(initialSailXPosition + (sailSpacing * i), yPosition - 10, initialSailXPosition + (sailSpacing * i), yPosition);
line(initialSailXPosition + (sailSpacing * i), yPosition - 40, initialSailXPosition + (sailSpacing * i), yPosition - 50);
// flag
fill(0);
rect(initialSailXPosition + (sailSpacing * i), yPosition - 50, 10, 5);
// jolly roger
stroke(255);
line(initialSailXPosition + (sailSpacing * i) + 2, yPosition - 49, initialSailXPosition + (sailSpacing * i) + 8, yPosition - 46);
line(initialSailXPosition + (sailSpacing * i) + 8, yPosition - 49, initialSailXPosition + (sailSpacing * i) + 2, yPosition - 46);
stroke(0);
}

// draw the portholes
for (int i = 0; i < portholeCount; i++) {
// portholes
fill(0);
ellipse(xPosition+(15*i),yPosition+10,5,5);
}

// ship has left the screen
if (backOfShipXPosition <= 0) {
// start again
initialise();
}

}
}

Tuesday, 31 March 2009

Processing.js

I've been messing with the javascript version of Processing, Processing.js
Annoyingly blogspot remove any script tags I add, so instead I've uploaded it to my own website, and created an iframe here. However, it is running totally in javascript, not an applet

I've had a few small issues with it, as the whole of Processing hasn't been converted to javascript yet, but they were only small and I got it working pretty easily

Check it out below (it's not finished yet!):

Saturday, 21 February 2009

Chunk 13 - FINAL

And here it is, finally finished. Just the second program to go

While Statements

The while statement, like a for statement, repeats a number of times executing the code inside the statement each time. However, whilst for statements repeat for a set number of times (iterations), while statements repeat as long as the boolean condition is true – the loops exits when the condition is false. In this respect, a while statement is like an if statement that is repeated until the condition is no longer true

To demonstrate while statements in Processing, we will use the point() function inside the draw() method to create dots on the screen. The point() function simply draws a one-pixel point at the coordinates given as arguments to the function in the form

point(x, y);

where x is the number of pixels along the horizontal axis and y is the number of pixels down the vertical axis. So, for example, the function call

point(10, 20);

will draw a point at the coordinate (10, 20) which is 10 pixels from the left of the window, and 20 pixels from the top. In order to see what the code is doing, we will also use the print() and println() functions to display the location of each point by printing the coordinates to the console (the only difference between these 2 is that println() creates a new line). So, for example

println("point: " + 10);

results in the console output:



Figure 1: Console output
A simple example of a while statement, shown below, might simply loop until the value of a variable reaches a certain value, in this case 19 (as we are using < 20)
// set the current point as the start point

int i = 0;
// while i is less than 20
while (i < 20) {
// output the value of i
println(i);
//add 1 to i
i++;
}

Of course, this isn't a very interesting use of Processing, so a slightly more complicated while statement, shown below, will print a line of dots, using the point() function, and also output the coordinates of the dots so we can see what it is doing

// set the current point as the start point
int currentPoint = 0;
// while the current point is less than the end point
while (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
println("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;
}

This will produce the output below – a screen with a lot of dots across it.



Figure 2: Points on the screen

If we converted this into an if statement, rather than a while statement, you will be able to see the difference

// set the current point as the start point
int currentPoint = 0;
// if the current point is less than the end point
if (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
println("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;
}

Although it is quite hard to see, in the screenshot below you should be able to see a single dot on the left. The if statement has only created one dot, whereas the while statement kept creating dots until it's condition (currentPoint < width) was false i.e. when currentPoint reaches the width of the window



Figure 3: Single point on the screen

Exit condition

The loop will exit at the point that the condition is checked and found to be false, not at the point that the condition becomes false. Therefore the remainder of the loop iteration will complete and the loop will exit when the condition is evaluated. An analogy for this is a runner having to complete the lap, even though someone has won


// set the current point as the start point
int currentPoint = 0;
// while the current point is less than the end point
while (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
print("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;
// draw another point at coordinates (currentPoint, 40)
point(currentPoint, 40);
println(" after");
}

In the above example, the loop iteration continues even though the value of currentPoint is no longer less-than width. The point is still drawn and the 'after' output is still printed to the console because that iteration still completes before the while statement exits when the condition is re-evaluated.

Using Arrays

In the above examples, we specify the gap between the points by incrementing the currentPoint variable (the x-axis coordinate) by a set value of 5. What if, though, we wanted to vary the gap between each point by an arbitrary value by specifying the x-axis coordinate of each point? This would be possible using the above examples, but the resulting code would be untidy and overly-complicated

A common use for while statements is to access elements in an array. As the body of the statement will be executed multiple times, it can be used to access each element of the array in turn, ending when the last element is reached. This provides a convenient method of accessing every element in the array. Using an array, we can change our point program to specify the x-axis position of the points

int i = 0;
// specify the x-axis coordinates
int[] array = {11,23,35,47,59,67,75,83,91};
// loop over the array
while (i < array.length) {
point(array[i], 20);
i++;
}

Using a counter, each element in the array can be accessed in turn and the value given as the x-axis coordinate to the point function. The result is shown in the screenshot below




Figure 4: Variable points using an array

Compare to for loop

You may be wondering at this point why there is a need for a for statement if a while statement can do the same thing. If they seem similar it is because they are – a for statement provides a simple way of using a counter to define the number of times the statement loops. This means that the number of times the statement runs is known. Although a while statement can use a counter, as in the above examples, this need not be (and often isn't) the case. While statements with counters tend not to look as neat as for statements. For instance, the example above using a for statement would look like:

// specify the x-axis coordinates
int[] array = {11,23,35,47,59,67,75,83,91};
// loop over the array
for(int i = 0; i < array.length; i++) {
point(array[i], 20);
}

The main difference, however, lies in how you know when to exit the loop. The condition for exiting a while statement is not usually as straightforward – it is likely that you will not know exactly how many times it will loop when you write it, as the value of the condition will be determined while the program is running. It is also important to remember that it is possible (and a very common error) to accidentally write a while statement that will loop forever – an infinite loop – because the condition never becomes false

int i = 0;
// specify the x-axis coordinates
int[] array = {11,23,35,47,59,67,75,83,91};
// loop over the array
while (i < array.length) {
point(array[i], 20);
// remove the i++ so it loops forever
println(i);
}

In the above example, the while statement loops forever because we never increment the value of i and so the condition will forever be true. If you run this, you will see the value of i being printed on the console, but you won't see the points on the screen because the draw method will never end. If you do run this, you can stop the program by closing the Processing window

It is therefore necessary to have a well-defined condition that you know will exit at some point. A badly designed condition can result in an infinite loop that you didn't intend. This time we will create a 'target' square, and draw points until one of them lands in the target square, or we 'run out' of points. We will need to make sure that we know to exit the loop

int i = 0;
int yPoint = 100;
int[] array = {11,23,35,47,59,67,75,83,91};
// draw the target square
rect(60, 80, 40, 40);
boolean keepLooping = true;
// loop until told not to
while (keepLooping && i < array.length) {
// draw the point
point(array[i], yPoint);
// if the point is in the square
if (array[i] >= 60 && array[i] <= 100) {
if (yPoint >= 80 && yPoint <= 120) {
// stop looping
keepLooping = false;
}
}
i++;
}

In this example, we exit the while statement when a point lands in the square by checking the location of the point to see if it falls within the region the square occupies, or if the variable i reaches the end of the array. This ensures we never try to access an element beyond the size of the array. The screenshot below shows what happens when we run this – the loop ends before the end of the array is reached because a point lands in the target square




Figure 5: Points hitting the square target

There are various ways of using the condition to determine how many times the statement will execute. Any statement can be used as the condition provided it evaluates or returns a boolean value. This could be:

- a counter that is tested in the condition (like an if statement)
- a variable that is tested for some criteria
- a boolean that is set it to false to exit
- a method that returns a boolean


do.. while statements

Just as it is possible to have a while statement that loops forever, it is also possible to have one that never executes if the condition is never met. If the condition never evaluates to true, the loop body will never be executed. However, sometimes you might always want a section of code to be executed even if the condition is not met. An example of this is requesting input from the user until they enter an exit character – you would always want to request the input, even if they enter the exit character first time. Using a while statement, the request code to be executed would have to be repeated. For example

request input from user
while (input is not a *)
do something
request input from the user

In this situation, there is another type of loop statement that can be used – a do..while statement. A do..while statement is like a while statement but evaluates the condition after the body of the loop has been executed. This means that the code inside the body is always executed at least once – if the condition is found to be false, the loop will exit at that point having already executed the code. For instance

do
request input from user
do something
while (input is not a *)

To demonstrate this, we can use the previous example, but set the keepLooping variable to false. Using a while statement, this would prevent the statement code from being executed. Using a do..while statement, however, the statement will run once, displaying a single point, before the condition is found to be false.

int i = 0;
int yPoint = 100;
int[] array = {11,23,35,47,59,67,75,83,91};
// draw the target square
rect(60, 80, 40, 40);
boolean keepLooping = false;

do {
// draw the point
point(array[i], yPoint);
// if the point is in the square
if (array[i] >= 60 && array[i] <= 100) {
if (yPoint >= 80 && yPoint <= 120) {
// stop looping
keepLooping = false;
}
}
i++;
} while (keepLooping && i < array.length);

It can be dangerous to always execute the code inside the loop statement if you do not know what the effect of that would be. If we didn't use the keepLooping variable, and the array was empty, accessing the element at array[i] would cause an ArrayIndexOutOfBoundsException. Using a while statement, the loop body would never be executed, so no exception would occur.

If there is a chance that the code should never be executed, then a while statement would be more appropriate. Do .. while statements should only be used when you know that need the loop code to be executed as least once. As such, they are seldom used, but do provide a useful way of eliminating duplicate code.

Putting it all together – TV static

To put together what you have learned so far, we will write a program using while statements that recreates television static. To do this, we will create an array of colours for the dots we will display, and use the random() function in Processing to randomise the colours we create. Processing also gives us access to every pixel on the screen using the pixels variable. We can use this to set the colour of each pixel by looping over the pixels array and setting the colour, which we will also randomise. This will give us a random colour for each point on the screen.

private int[] colours;

void setup() {
// set the window size
size(500,500);
colours = new int[10];
// load random colours
int i = 0;
while(i < colours.length) {
colours[i] = color((int) random(0, 256), (int) random(0, 256), (int) random(0, 256));
i++;
}
}

void draw() {

loadPixels();
// change every pixel every time
int i = 0;
while(i < pixels.length) {
pixels[i] = colours[(int)random(0, colours.length)];
i++;
}
updatePixels();
}

This gives us the TV static-effect shown below




Figure 6: Ten-colour TV static

Of course, the colours you generate may well be different due to the random colours we created. You can change the number of colours generated by simply changing the size of the colours array. For example, changing it to 2 gives the effect




Figure 7: Two-colour TV static

Tuesday, 10 February 2009

First 2000 words (draft)

While Statements

The while statement, like a for statement, repeats a number of times executing the code inside the statement each time. However, whilst for statements repeat for a set number of times (iterations), while statements repeat as long as the boolean condition is true – the loops exits when the condition is false. In this respect, a while statement is like an if statement that is repeated until the condition is no longer true

To demonstrate while statements in Processing, we will use the point() function inside the draw() method to create dots on the screen. The point() function simply draws a one pixel point at the coordinates given as arguments to the function in the form
point(x, y);
where x is the number of pixels along the horizontal axis and y is the number of pixels down the vertical axis. So, for example, the function call
point(10, 20);
will draw a point at the coordinate (10, 20) which is 10 pixels from the left of the window, and 20 pixels from the top. In order to see what the code is doing, we will also use the print() and println() functions to display the location of each point by printing the coordinates to the console (the only difference between these 2 is that println() creates a new line). So, for example
println("point: " + 10);
results in the console output
[[[screenshot]]]
A simple example of a while statement, shown below, might simply loop until the value of a variable reaches a certain value, in this case 19 (as we are using < 20)

// set the current point as the start point
int i = 0;
// while i is less than 20
while (i < 20) {
// output the value of i
println(i);
//add 1 to i
i++;
}
// stop the draw method from executing again
noLoop();

Of course, this isn't a very interesting use of Processing, so a slightly more complicated while statement, shown below, will print a line of dots, using the point() function, and also output the coordinates of the dots so we can see what it is doing

// set the current point as the start point
int currentPoint = 0;
// while the current point is less than the end point
while (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
println("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;
}
// stop the draw method from executing again
noLoop();

This will produce the output below – a screen with a lot of dots across it.

[[[screenshot]]]

If we converted this into an if statement, rather than a while statement, you will be able to see the difference

// set the current point as the start point
int currentPoint = 0;
// if the current point is less than the end point
if (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
println("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;
}
// stop the draw method from executing again
noLoop();

Although it is quite hard to see, in the screenshot below you should be able to see a single dot on the left. The if statement has only created one dot, whereas the while statement kept creating dots until it's condition (currentPoint < width) was false i.e. when currentPoint reaches the width of the window

[[[screenshot]]]

Exit condition


The loop will exit at the point that the condition is checked and found to be false, not at the point that the condition becomes false. Therefore the remainder of the loop iteration will complete and the loop will exit when the condition is evaluated

// set the current point as the start point
int currentPoint = 0;
// while the current point is less than the end point
while (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
print("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;

point(currentPoint, 40);
println(" after");
}
// stop the draw method from executing again
noLoop();

In the above example, the loop iteration continues even though the value of currentPoint is no longer less-than width. The point is still drawn and the 'after' output is still printed to the console because that iteration still completes before the while statement exits when the condition is re-evaluated.

Using Arrays

In the above examples, we specify the gap between the points by incrementing the currentPoint variable (the x-axis coordinate) by a set value of 5. What if, though, we wanted to vary the gap between each point by an arbitrary value by specifying the x-axis coordinate of each point? This would be possible using the above examples, but the resulting code would be untidy and overly-complicated

A common use for while statements is to access elements in an array. As the body of the statement will be executed multiple times, it can be used to access each element of the array in turn, ending when the last element is reached. This provides a convenient method of accessing every element in the array. Using an array, we can change our point program to specify the x-axis position of the points

int i = 0;
// specify the x-axis coordinates
int[] array = {10,20,30,40,50,60};
// loop over the array
while (i < array.length) {
point(array[i], 20);
i++;
}

noLoop();

Using a counter, each element in the array can be accessed in turn and the value given as the x-axis coordinate to the point function. The result is shown in the screenshot below

[[[screenshot]]]

Compare to for loop

You may be wondering at this point what the point of a for statement is if a while statement can do the same thing. If they seem similar it is because they are – a for statement provides a simple way of using a counter to define the number of times the statement loops. This means that the number of times the statement runs is known. However, the difference lies in how you know when to exit the loop. Although a while statement can use a counter as in the above examples, this need not (and often isn't) the case. While statements with counters tend not to look as neat as for statements. As an example, the example above using a for statement would look like:

// specify the x-axis coordinates
int[] array = {11,23,35,47,59,67,75,83,91};
// loop over the array
for(int i = 0; i < array.length; i++) {
point(array[i], 20);
}

noLoop();

The condition for exiting a while statement is not usually as straightforward – it is likely that you will not know exactly how many times it will loop when you write it as the value of the condition will be determined while the program is running. It is also important to remember that it is possible to write a while statement that will loop forever – an infinite loop – because the condition never becomes false

int i = 0;
// specify the x-axis coordinates
int[] array = {11,23,35,47,59,67,75,83,91};
// loop over the array
while (i < array.length) {
point(array[i], 20);
// remove the i++ so it loops forever
println(i);
}

noLoop();

In the above example, the while statement loops forever because we never increment the value of i and so the condition will forever be true. If you run this, you will see the value of i being printed on the console, but you won't see the points on the screen because the draw method will never end. If you do run this, you can stop the program by closing the Processing window

It is therefore necessary to have a well-defined condition that you know will exit at some point. A badly designed condition can result in an infinite loop that you didn't intend. This time we will create a 'target' square, and draw points until one of them lands in the target square, or we 'run out' of points. We will need to make sure that we know to exit the loop

int i = 0;
int yPoint = 100;
int[] array = {11,23,35,47,59,67,75,83,91};
// draw the target square
rect(60, 80, 40, 40);
boolean keepLooping = true;
// loop until told not to
while (keepLooping && i < array.length) {
// draw the point
point(array[i], yPoint);
// if the point is in the square
if (array[i] >= 60 && array[i] <= 100) {
if (yPoint >= 80 && yPoint <= 120) {
// stop looping
keepLooping = false;
}
}
i++;
}

noLoop();

In this example, we exit the while statement when a point lands in the square by checking the location of the point to see if it falls within the region the square occupies, or if the variable I reaches the end of the array. This ensures we never try to access an element beyond the size of the array. The screenshot below shows what happens when we run this – the loop ends before the end of the array is reached because a point lands in the target square

[[[screenshot]]]

There are various ways of using the condition to determine how many times the statement will execute. Any statement can be used as the condition provided it evaluates or returns a boolean value. This could be:

- a counter that is tested in the condition (like an if statement)
- a variable that is tested for some criteria
- a boolean that is set it to false to exit
- a method that returns a boolean


do.. while statements

Just as it is possible to have a while statement that loops forever, it is also possible to have one that never executes if the condition is never met. If the condition never evaluates to true, the loop body will never be executed. However, sometimes you might always want a section of code to be executed even if the condition is not met. An example of this is requesting input from the user until they enter an exit character – you would always want to request the input, even if they enter the exit character first time. Using a while statement, the request code to be executed would have to be repeated.

In this situation, there is another type of loop statement that can be used – a do..while statement. A do..while statement is like a while statement but evaluates the condition after the body of the loop has been executed. This means that the code inside the body is always executed at least once – if the condition is found to be false, the loop will exit at that point having already executed the code

To demonstrate this, we can use the previous example, but set the keepLooping variable to false. Using a while statement, this would prevent the statement code from being executed. Using a do..while statement, however, the statement will run once, displaying a single point, before the condition is found to be false

int i = 0;
int yPoint = 100;
int[] array = {11,23,35,47,59,67,75,83,91};
// draw the target square
rect(60, 80, 40, 40);
boolean keepLooping = false;

do {
// draw the point
point(array[i], yPoint);
// if the point is in the square
if (array[i] >= 60 && array[i] <= 100) {
if (yPoint >= 80 && yPoint <= 120) {
// stop looping
keepLooping = false;
}
}
i++;
} while (keepLooping && i < array.length);

noLoop();

It can be dangerous to always execute the code inside the loop statement if you do not know what the effect of that would be. If we didn't use the keepLooping variable, and the array was empty, accessing the element as array[i] would cause an ArrayIndexOutOfBoundsException. Using a while statement, the loop body would never be executed, so no exception would occur.

If there is a chance that the code should never be executed, then a while statement would be more appropriate. Do .. while statements should only be used when you know that need the loop code to be executed as least once. As such, they are seldom used, but do provide a useful way of eliminating duplicate code

Putting it all together

Sunday, 1 February 2009

First 1500 words (draft)

While Statements

The while statement, like a for statement, repeats a number of times executing the code inside the statement each time. However, whilst for statements repeat for a set number of times (iterations), while statements repeat as long as the boolean condition is true – the loops exits when the condition is false. In this respect, a while statement is like an if statement that is repeated until the condition is no longer true

To demonstrate while statements in Processing, we will use the point() function inside the draw() method to create dots on the screen. The point() function simply draws a one pixel point at the coordinates given as arguments to the function in the form
point(x, y);
where x is the number of pixels along the horizontal axis and y is the number of pixels down the vertical axis. So, for example, the function call
point(10, 20);
will draw a point at the coordinate (10, 20) which is 10 pixels from the left of the window, and 20 pixels from the top. In order to see what the code is doing, we will also use the print() and println() functions to display the location of each point by printing the coordinates to the console (the only difference between these 2 is that println() creates a new line). So, for example
println("point: " + 10);
results in the console output
[[[screenshot]]]
A simple example of a while statement


// set the current point as the start point
int currentPoint = 0;
// while the current point is less than the end point
while (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
println("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;
}
// stop the draw method from executing again
noLoop();


This will produce the output below – a screen with a lot of dots across it.

[[[screenshot]]]

If we converted this into an if statement, rather than a while statement, you will be able to see the difference


// set the current point as the start point
int currentPoint = 0;
// if the current point is less than the end point
if (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
println("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;
}
// stop the draw method from executing again
noLoop();


Although it is quite hard to see, in the screenshot below you should be able to see a single dot on the left. The if statement has only created one dot, whereas the while statement kept creating dots until it's condition (currentPoint < width) was false i.e. when currentPoint reaches the width of the window

[[[screenshot]]]

Exit condition

The loop will exit at the point that the condition is checked and found to be false, not at the point that the condition becomes false. Therefore the remainder of the loop iteration will complete and the loop will exit when the condition is evaluated


// set the current point as the start point
int currentPoint = 0;
// while the current point is less than the end point
while (currentPoint < width) {
// draw a single pixel point at that point, 20 pixels down
point(currentPoint, 20);
print("point:" + currentPoint);
// increment by 5 to leave a gap
currentPoint +=5;

point(currentPoint, 40);
println(" after");
}
// stop the draw method from executing again
noLoop();


In the above example, the loop iteration continues even though the value of currentPoint is no longer less-than width. The point is still drawn and the 'after' output is still printed to the console because that iteration still completes before the while statement exits when the condition is re-evaluated.

Compare to for loop

You may be wondering at this point what the point of a for statement is if a while statement can do the same thing. If they seem similar it is because they are – a for statement provides a simple way of using a counter to define the number of times the statement loops. This means that the number of times the statement runs is known. However, the difference lies in how you know when to exit the loop. Although a while statement can use a counter as in the above examples, this need not (and often isn't) the case. While statements with counters tend not to look as neat as for statements. As an example, the first example using a for statement would look like:


// loop from 0 to the width of the window
for (int i = 0; i < width; i+=5) {
// draw a single pixel point at that point, 20 pixels down
point(i, 20);
println("point:" + i);

}
// stop the draw method from executing again
noLoop();


The condition for exiting a while statement is not usually as straightforward – it is likely that you will not know exactly how many times it will loop when you write it as the value of the condition will be determined while the program is running. It is also important to remember that it is possible to write a while statement that will loop forever – an infinite loop – because the condition never becomes false


while (1 == 1) {
// create random coordinates
int xPoint = parseInt(random(0, width));
int yPoint = parseInt(random(0 , height));
// draw the point
point(xPoint, yPoint);
println(xPoint + " " + yPoint);
}


In the above example, the while statement loops forever because 1 is always equals to 1. If you run this, you will see the points being printed on the console, but you won't see the points on the screen because the draw method will never end. If you do run this, you can stop the program by closing the Processing window

It is therefore necessary to have a well-defined condition that you know will exit at some point. A badly designed condition can result in an infinite loop that you didn't intend. This time we will create a 'target' square in the centre of the window, and draw random points until one of them lands in the target square. We will need to make sure that we know to exit the loop


// draw the target square
rect((width/2)-20, (height/2)-20, 40, 40);
boolean keepLooping = true;
// loop until told not to
while (keepLooping) {
// create random coordinates
int xPoint = parseInt(random(0, width));
int yPoint = parseInt(random(0 , height));
// draw the point
point(xPoint, yPoint);
println(xPoint + " " + yPoint);

// if the point is in the square
if (xPoint >= (width/2)-20 && xPoint <= (width/2)+20) {
if (yPoint >= (height/2)-20 && yPoint <= (height/2)+20) {
// stop looping
keepLooping = false;
}
}

}

noLoop();


In this example, we exit the while statement when a point lands in the square by checking the location of the point to see if it falls within the region the square occupies. If we hadn't written this so well, we could easily never set the keepLooping variable to false and therefore inadvertently created an infinite loop

There are various ways of using the condition to determine how many times the statement will execute. Any statement can be used as the condition provided it evaluates or returns a boolean value. This could be:

-a counter that is tested in the condition (like an if statement)
-a variable is tested for some criteria
-a boolean that is set it to false to exit
-a method that returns a boolean



while using arrays
- simple array example
- using a boolean
(possibly using the result of a method call)


do.. while

Just as it is possible to have a while statement that loops forever, it is also possible to have one that never executes if the condition is never met. However, sometimes you might always want a section of code to be executed even if the condition is not met. An example of this is [think of an example]
Using a while statement, the code to be executed would have to be repeated – at the very least a method would have to be called twice (example?)

In this situation, there is another type of loop statement that can be used – a do..while statement. A do..while statement is like a while loop but evaluates the condition after the body of the loop has been executed. This means that the code inside the body is always executed at least once – if the condition is found to be false, the loop will exit at that point having already executed the code

example



- using arrays

It can be dangerous to always execute the code inside the loop statement if you do not know what the effect of that would be. [explain]. If there is a chance that the code should never be executed, then a while statement would be more appropriate. Do .. while statements should only be used when you know that need the loop code to be executed as least once. As such, they are seldom used, but do provide a useful way of eliminating duplicate code

Putting it all together

- big example


Tuesday, 27 January 2009

First 1000 words (draft)

While Statements

The while statement, like a for statement, repeats a number of times executing the code inside the statement each time. However, whilst for statements repeat for a set number of times (iterations), while statements repeat as long as the boolean condition is true – the loops exits when the condition is false. In this respect, a while statement is like an if statement that is repeated until the condition is no longer true

To demonstrate while statements in Processing, we will use the point() function to create dots on the screen. The point() function simply draws a one pixel point at the coordinates given as arguments to the function in the form
point(x, y);

where x is the number of pixels along the horizontal axis and y is the number of pixels down the vertical axis. So, for example, the function call
point(10, 20);

will draw a point at the coordinate (10, 20) which is 10 pixels from the left of the window, and 20 pixels from the top

A simple example of a while statement


// set the current point as the start point
int currentPoint = 0;
// while the current point is less
//than the width of the window
while (currentPoint < width) {
// draw a single pixel point at that
//point, 20 pixels down
point(currentPoint, 20);
// increment by 2 to leave a gap
currentPoint +=2;
}


This will produce the output below – a screen with a lot of dots across it.

screenshot

If we converted this into an if statement, rather than a while statement, you will be able to see the difference


// set the current point as the start point
int currentPoint = 0;
// while the current point is less
// than the end point
if (currentPoint < width) {
// draw a single pixel point at that
// point, 20 pixels down
point(currentPoint, 20);
// increment by 2 to leave a gap
currentPoint +=2;
}


Although it is quite hard to see, in the screenshot below you should be able to see a single dot on the left. The if statement has only created one dot, whereas the while statement kept creating dots until it's condition (currentPoint < width) was false i.e. when currentPoint reaches the width of the window

screenshot

Exit condition

The loop will exit at the point that the condition is checked and found to be false, not at the point that the condition becomes false. Therefore the remainder of the loop iteration will complete and the loop will exit when the condition is evaluated

example

In the above example, the loop continues even though the value of [whatever the condition is]. The [whatever the line is] is still [run/output?] because that iteration still completes before the while statement exits when the condition is re-evaluated.

Compare to for loop

You may be wondering at this point what the point of a for statement is if a while statement can do the same thing. If they seem similar it is because they are – a for statement provides a simple way of using a counter to define the number of times the statement loops. This means that the number of times the statement runs is known. However, the difference lies in how you know when to exit the loop. Although a while statement can use a counter, this need not (and often isn't) the case. While statements with counters tend not to look as neat as for statements.

compare for and while examples

The condition for exiting a while statement is not usually as straightforward – it is likely that you will not know exactly how many times it will loop when you write it as the value of the condition will be determined while the program is running. It is also important to remember that it is possible to write a while statement that will loop forever – an infinite loop – because the condition never becomes false

-- deliberate infinite loop example (tell them how to exit it)

It is therefore necessary to have a well-defined condition that you know will exit at some point. A badly designed condition can result in an infinite loop that you didn't intend

-- give examples – one good one bad (checking a number that never occurs using ==)

There are various ways of using the condition to determine how many times the statement will execute

set a counter and test in the condition (like an if statement)
test a variable for some criteria
set a boolean and set it to false to exit
call a method that returns a boolean



while using arrays
- simple array example
- using a boolean
(possibly using the result of a method call)


do.. while

Just as it is possible to have a while statement that loops forever, it is also possible to have one that never executes if the condition is never met. However, sometimes you might always want a section of code to be executed even if the condition is not met. An example of this is [think of an example]
Using a while statement, the code to be executed would have to be repeated – at the very least a method would have to be called twice (example?)

In this situation, there is another type of loop statement that can be used – a do..while statement. A do..while statement is like a while loop but evaluates the condition after the body of the loop has been executed. This means that the code inside the body is always executed at least once – if the condition is found to be false, the loop will exit at that point having already executed the code

example



- using arrays

It can be dangerous to always execute the code inside the loop statement if you do not know what the effect of that would be. [explain]. If there is a chance that the code should never be executed, then a while statement would be more appropriate. Do .. while statements should only be used when you know that need the loop code to be executed as least once. As such, they are seldom used, but do provide a useful way of eliminating duplicate code

big example