Processing+-+Loops+Review

Loops are a wonderful way to do repeated things. In Processing, you have the draw loop, which repeats over and over.

There are two main ways to program loops in Processing. The first is a while loop: code format="java" while(loop condition) { //stuff happens repeatedly //update loop counter (optional) } code The while loop is a bit like a repeated if-statement. If you use a loop counter, you need to declare it first, outside of the loop. Here's an example: code format="java" int counter=0; while(counter < 10) { println(counter + " yay!"); counter = counter + 1; } code (and most programmers would use counter++ for the last line.)

Stop: Required to show: 1. Write a while loop that will print out the first 10 multiples of 5. (5, 10, 15, etc.) Yes - it must be a while loop. 2. Write a function that uses a while loop to simulate a dice rolling (1 to 6, randomly) until a 6 is rolled, at which point it stops. Print out the roll each time.

Done? Do for loops: That was a bit messy! While loops are really great when we **don't know** how many times the loop will run! For loops are good when we **know** how many times the loop will run.

Here's the general form: code format="java" for(initialize counter; loop condition; update counter) { //do stuff } code So, for loops are pretty much the same as while loops, but they have all loopy-components on one line. Here's an example: code format="java" for(int i=0; i<10; i++) { println("Hello!" + i); } code (Notice that I've switched to i for my counter. This is REALLY common because i is shorter to type than counter.)

Stop: Required to go on: 1. Write a for loop that counts down from 10 to 1. 2. Write function that returns the factorial of a number n. Factorial (noted by !) is defined as math n! = n \times (n-1) \times \cdots \times 2 \times 1 math You may assume that n is always greater than 1.