# Procession Tutorial 6

Loops add power and convenience to creative, interactive programs.

Section 1. Loops

Loops use iteration – a process of repeating rules. Loops are designed to save time because less lines of code are needed to tell the computer what we want it to do. Basically, loops are concise instructions. They repeat things, this is iteration.

Here’s a real world example of how a loop saves time…

A. The long way:

Start at mark zero and then jump 5′.

B. The loop way:

Start at mark zero and then jump in increments of 5′ until you get to the 25′.

This is a much simpler way of saying the same thing.

This sentence uses one idea in repetition – it is a loop.

In code, loops efficiently cover a lot of territory with a short amount of text.

Section 2. Introducing the “WHILE” Loop

The while loop employs the “if-then” boolean test condition. If the results of the loop test = true, then the {}instructions are executed. If the results of the loop test = false, then the program moves onto the next line of code (it doesn’t loop back).

More on the “WHILE” loop in a little bit…

Exercise 1:

1A.

Enter the code below to draw one rectangle:

1B.

Review Question: What is the one line of code that can be added so the rectangle repeats itself infinitely downwards every 20 pixels?

Hint: Write an “Assignment Operator.”

1C.

What if we don’t want the rectangle to repeat infinitely?

How do we program it to stop right at the bottom of the canvas?

One option is the constrain() function. Code your solution.

1D.

But, in some conditions a while{}” loop is useful as a solution. Code the following:

This picture ends up the same as the program using constrain()  but this time we used a “while{}” loop. Analyze the code and explain how the while{} loop works (as a comment in your code).

1E.

What did you notice that was different between the loading of the white rectangles with the constrain() solution versus the while{} loop solution? Why do they animate differently when you push play?

Exercise 2

2a. Figure out the missing lines of code in the box below so your program draws the following ellipse pattern. Note the how the shapes change in scale and the variation of color. One variable will do alot of work here!

Here’s the starter code, try a few tests before peeking at answer below…

2b. Comment on how did you with this exercises, what did you know and what did you struggle with?

Section 3. Exit Conditions

As is with all programming, a logical code structure is critical for getting loops to work for you. Successful loop programming has exit conditions. Exit conditions signal the loop to end when a specific condition is met.

Regular Language Example:

Keep the green color palette of the Centipede’s arcade screen the same until the player kills all the centipedes. If player kills all the centipedes then change the screen colors (exit green color palette). Without the exit condition, the board won’t change color.

If your are working with loops and you don’t program an exit condition then your computer will be caught in an infinite loop.

Infinite loops can clog up your processor so much that your computer crashes.

Give it a whirl:

What is happening with the code? Why might Processing crash?

1) int x starts out as zero.

2) the while{} loop says: “as long as x is less than 10”

3) use the assignment operator to decrease x by 1. –>this never stops!, no exit condition for the while loop.

An infinite loop (or endless loop) is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over. In older operating systems with cooperative multitasking, infinite loops normally caused the entire system to become unresponsive. With the now-prevalent preemptive multitasking model, infinite loops usually cause the program to consume all available processor time, but can usually be terminated by the user.

Be careful with your future programs, a slight typo in your code might create an infinite loop.

To avoid this when coding loops,

make sure to check your logic and make sure there is an viable exit condition.

Section 4. Code Short Cuts

As we begin to read and write loops in our code, we will soon discover that we call the computer to do many actions with the number 1. Below are some shorthand ways to write the number 1 in logical code expressions.

Shortcuts are designed to save you time so you can write your code faster.

At first they may not click – that is ok. You don’t have to use them right away (although eventually you will want to).

It is important to be familiar with the shortcuts since you will see them in the future

and will need to understand what you are looking at when examining new code models.

Section 5. For Loops

There is a shorthand version of the while{} loop called the for{} loop and it makes it easy to program simple incremental loops. Just like the while{} loop, the for loop tests if conditions are true or false and then either repeats the loop or exits onto a new condition. The big difference is that the for{} loop is specific for repetitive counting.

Exercise 3

3a: Type in the following code and see how a for{} loop generates 16 red lines:

Focus on this line of code to answer the following questions:

3b. Where is the y variable declared in this for{} loop? How is this different from where we declared custom variables in the past?

3c. What is the condition that for{} loop tests?

3d. What happens to the y variable if the condition tests true?

3e. Why does the line draw 16 times, explain in detail how the variable “y” works in the line() command with the for{} loop?

IMPORTANT NOTE:

A WHILE{} LOOP CAN DO THE SAME THING AS A FOR{} LOOP

In general a while{} loop is used if you want an action to repeat itself until a certain condition is met such as an if statement.

And a for{} loop is used when you want to count through an object or system.

But, it is really up to the programmer and how they like to arrange their code logic.

Exercise 4

Back to this design:

Fill in the blanks below so the code reproduces the circle variations using a for loop.

Peek at the answer when you must

Exercise 5

In the following exercise there are several loops.

Match the code with the picture without using Processing.

Assume each example starts with the same four lines of initial code.

Section 6. Local vs. Global Variables

As you probably noticed, there has been a shift in how we declared our variables. Up until the for loop, variables were always declared at the top of our code. For our beginning stages of programming, it made sense to do it this way. But, as our programs gets more and more intricate, we will use variables for different purposes. Some variables need to be accessible all the time – these are global variables. But, in other cases we may only need a variable for a short bit of code – these are local variables.

Real World Example:

A post-it note reminder that you have dinner plans tonight would be a local variable. You only need to access the note for a short period.

A post-it note reminder of your bank account number would be a global variable because more than likely you will access this reminder many times over a long period of time.

In the following screenshots you can see the placement of local and global variables in the code…

Example Placement of “Local” Variables:

Example Placement of “Global” Variables:

So what? Why not just make all variables global and keep things simple?

Making all variables global causes the computer to work harder.

This is because the computer is considering variables for every line of code in your program and the reality is that you may not need this.

In complex programs, unnecessary global variables may slow processor down.

Also, using local variables (and adding comments to your code), makes debugging complex lines of code easier.

Ultimately, it depends on what you need your program to do.

Sometimes you will be local and sometimes you will need to go global.

Section 7. When to Globalize

Try these two bits of code and compare your results:

The variable placement and animation is different in the above two models.

What do you notice about the two programs when you push play?

Important Note:

Processing does not update the display window until the end of draw() cycle is reached.

This is important to notice when using while and for loops.

While and for loops repeat actions within only one cycle.

This accounts for the differences

Exercise 6

6a.

Type and run the following gray scale animation code.

6b.

The println() command tells you what the value of mouseX() and the variable i becomes when you move the mouse. Use this information and analyze the code deeply to understand how the two local variables (“distance” and “i“) work with mouseX and absolute value abs() to make this grayscale gradient animation work.

–> Look again. Why do the rectangles go black when the mouse is rolled over them?

This is a puzzle, you have all the clues you need in the program and the comments to answer this.

Make sure you understand before moving on.

–> Lastly, convert the above code so it uses a for” loop instead of a while” loop to achieve the same effect.

Exercise 7

Make the following randomly colored grid using two for loops.

Many solutions are possible. Play around and test your theories.

Work hard to solve the answer yourself before peeking at one possible solution here.

Exercise 8

In the previous exercise you nested two for loops to achieve the multi-color grid. Now, repeat this exercise using two nested while loops.

Peek at the answer when you are finished

If the above concepts aren’t clicking for you or if you would like a fun review of these coding ideas, then try watching the very animated and informal free video tutorials by NYU professor and Processing champion, Daniel Shiffman.

The videos which reference this webpage:

While Loops

Two Loop Grid Exercise

For Loops

Variable Scope

Loop vs Draw, Important Distinction!

Nested Loops

Also, For Loops are explained here in another way by Jose Sanchez of the Plethora Project.