• No results found

The last step to perfecting the polygon is to generalize the function, so we can create a polygon of any side count. We can easily add a side count parameter to the polygon() function, but utilizing the new parameter will take a bit more work.

Update the signature of the polygon function to: void polygon(int sideCount, float radius)

The remaining challenge is to be able to dynamically change the number of vertices plotted, based on the argu- ment value passed to the sideCount parameter. Your current code manually creates three vertices, but there is no way to build upon this approach when the number of vertices is unknown until the function receives the argument value. The solution to this problem (and many, many other problems in programming) is to use a loop. We’ll take a brief digression to learn about loops and then return to perfect your polygon() function.

Loops

You learned a little about loops in theory in the last chapter. Loops are really quite simple. They allow you to run code repetitively as long as a conditional test evaluates to true, similar to what you learned about with if statements. The basic logic in pseudocode is:

loop(boolean condition){

// continue to run while the condition is true }

Processing includes three structures for creating loops: ■ ■ for ■ ■ while ■ ■ do while

for and while loops behave similarly, and which one you choose is sometimes a matter of personal preference. However, there are certain problems that lend themselves more to one than to the other, which we’ll illustrate. do while loops offer a subtle variation to while loops, in that they are guaranteed to run at least one time, which is not the case with for and while loops. Let’s look at a few examples before applying them to the polygon() function. Example one outputs the values 0 to 99, first using a while loop and then a for loop.

while loop: int i = 0; while (i < 100) { println("i = " + i); i = i + 1; } for loop:

for (int i=0; i<100; i=i+1) { println("i = " + i); }

The first thing you’ll notice about the while loop is that the Boolean conditional test (i < 100) utilizes a variable external to the while loop. Because int i is declared outside of the loop, i is not local to the loop. In other words, i can be seen beyond the while loop. Next look at the for loop, which at first glance seems much more complicated than the while loop. Notice that the variable declaration int i occurs within the head of the loop, making it completely local to the loop; it can’t be seen outside of the loop’s curly braces (its block). Both loops will output exactly the same values: 0–99, and both loops also work by incrementing a counter variable i, in this case by 1. Technically, you can use any legal name you want for the loop counter variable, but there is a convention to use i, and then j, and then k if you need additional counters within the same loop structure. You can also increment or decrement the counter in both loops by any legal value or expression you’d like.

while loops are straightforward to understand. They continue to run while the test condition is true. If it’s always true you’ll get an infinite loop, which is generally a bad thing, as discussed in the last chapter. Infinite loops will make Processing lock up as control gets stuck within the loop, causing a standstill. It’s a very common error to accidentally generate an infinite loop, even by experienced coders. while loops always begin executing with a conditional test; if it evaluates to true, the loops runs, and to false, the loop is skipped. while loops are especially

void findValue(int val) { boolean isFound = false; int steps = 0; while (!isFound) { steps = steps + 1; if (1+int(random(100)) == val) { isFound = true; } }

println("It took " + steps + " steps to find " + val+"."); } // findValue

We snuck some new code snuck in this example, int(random(100)). The random() function returns a float value, but the example is checking for an integer. Processing’s int() function truncates float values to inte- gers by removing any numbers after the decimal point. This means that the following values would all be con- verted to 3: 3.0001, 3.567, 3.9998. Processing also includes a round() function which rounds a value to the nearest integer value.

Try This: Search for a value between a different range of numbers.

for loops use a very condensed syntax that puts the counter declaration, conditional test, and incrementation (or decrementation) all in the head of the loop. Notice these three elements are separated by two semi-colons. The loop begins execution by declaring and initializing the counter, which only happens once. Then the conditional test occurs; if it evaluates to true, the loop executes; if false, the loop is skipped. After each iteration of the loop, the counter is incremented by the rule in the third part of the loop head. In general, for loops are most useful when you know exactly how many iterations the loops should run.

What’s significant about both while and for loops is that they are not guaranteed to run even once if the starting conditional test evaluates to false. For example, in the earlier loop examples that printed out all the values from 0 to 99, if we had started i at 100 instead of 0, neither loop would have run. Try running these:

//while loop that won't run:

int i = 100; while (i < 100) { println("i = " + i); i = i + 1;

}

//for loop that won't run:

for (int i=100; i<100; i=i+1) { println("i = " + i);

}

The do while loop is a variation of the while loop guaranteed to run at least once. It uses an inverted structure, running the block prior to the conditional test, shown next.

// This loop will run once even though // the starting condition is false int i = 100;

do {

println("i = " + i); i =i+1;

} while (i<100);

Logically it would seem that this loop shouldn’t run, as the counter i is never less than 100. However, do while loops always execute at least once. This can be useful if you need to ensure that some programmatic event always occurs, regardless of the initial state of the program.