# September 23-25

## September 23-25

(updated by Michelle)

Exam update: If you are stressed about exam scores, take a deep breath. When the scores come out over the weekend, we will also be releasing a points-back packet. This is optional, but if you complete this packet by the end of the October 6th lab and hand it into your TA, you will get points back on the exam. How many points will depend on overall exam results and the correctness of your answers.

## Functions using return values

We talked more about defining functions and using the `return` statement to return a value to the function call expression.

For example, suppose you write an expression with a function call, e.g. `1 + f()`, and inside the definition of function `f` there is a return statement: `return 5;`. In this case, the value of the `return` expression, 5, becomes the value of `f()`, so after the `return` statement, we “return” to the original expression and compute 1 + 5.

So you now know about several types of functions. All functions do some sort of work like drawing something for you, printing something for you, or calculating something for you. Sometimes functions takes input, either using parameters or global variables. And you can mix and match the structure of these functions to create an appropriate behavior to your program.

Something to think about: Functions probably aren’t all that new to you. You see functions in math all the time that basically takes an input and then returns an output. You even see them in our everyday lives. For example, the human body is basically a program that uses many functions to do work. Eating is basically the function of taking in food, extracting what we need, and returning energy (amongst other things…) So look at the bigger picture of why it is important we have functions and really use them to give your code a meaningful structure.

## Arrays

Today we introduced arrays. Arrays are data structures that allow us to store multiple values of the same type. This goes hand-in-hand with iteration in for loops because you can traverse the array, get the value you need, and then do something with that value.

You should read about arrays in the textbook and w3schools readings, but here are some key things to remember:

• You access the elements of the array by its index.
• Arrays are zero-indexed so if you try to index into the array outside of the range 0 to the array length – 1, you will break everything. So watch your for loops carefully.
• Arrays only take values of the same type, so don’t try to make one array store strings and numbers.

With that said, here is the code we went over in class.

We started with a simple program with a single moving rect:

``````var x;
var y;
var dx;
var dy;
var col;

function setup() {
createCanvas(200, 200);
x = random(width);
y = random(height);
dx = random(-5, 5);
dy = random(-5, 5);
col = color(random(255), random(255), random(255));
}

function draw() {
background(200, 200, 200);
fill(col);
noStroke();
rect(x, y, 10, 10);
x += dx;
y += dy;
if (x > width) x = 0;
else if (x < 0) x = width;
if (y > height) y = 0;
else if (y < 0) y = height;
}
``````

We modified this program so that every number was replaced by an array of numbers and every computation on a set of variables was replaced by a for loop to do the computation on each element of each array.

Here’s the resulting program with 100 rects rather than 1 rect:

``````var x = []; // every variable now starts out as an empty array
var y = [];
var dx = []; // velocity in x direction (d for "delta" meaning change or difference)
var dy = []; // velocity in y direction
var col = []; // color of each rect wil be random

function setup() { // set random position, velocity, and color for 100 rects
createCanvas(200, 200);
for (i = 0; i < 100; i++) { // for loop initializing 100 values in each array
x[i] = random(width);
y[i] = random(height);
dx[i] = random(-5, 5);
dy[i] = random(-5, 5);
col[i] = color(random(255), random(255), random(255));
}
}

// update position and draw each of 100 rectangles
function draw() {
background(200, 200, 200);
noStroke();
for (i = 0; i < 100; i++) {  // for each rectangle ...
fill(col[i]);
rect(x[i], y[i], 10, 10);
x[i] += dx[i];
y[i] += dy[i];
// "wrap" logic: if you go off an edge, jump to the opposite edge
if (x[i] > width) x[i] = 0;        // wrap horizontally
else if (x[i] < 0) x[i] = width;
if (y[i] > height) y[i] = 0;       // wrap vertically
else if (y[i] < 0) y[i] = height;
}
}
``````

Here’s another use of arrays: A row of buttons where the “state” of the button is stored in an array of boolean (`true`/`false`) values. In this case if a button state is has the value `true`, then it should be red. Otherwise, is the value is `false`, then it should be green.

The code to click on buttons is crude and imprecise. It could be much better, but I kept in minimal in order to focus on the use of arrays.

A note about booleans: Booleans are types just like integers, floating points, and strings. They are not variables, but variables can be assigned the values of booleans. And just like numbers, booleans have their own operators. You’ve seen these before. Whenever you use `&&`, `||`, or `not`, you are performing an operation on boolean values much like addition and subtraction work for number values. Actually every conditional expression that you write evaluates to a boolean. For example, the expression `100 != 0` would evaluate to `true`. In addition, the expression `(100 != 0) && (100 % 2 == 1)` would be `false` since 100 is not an odd number. This is a very important concept because booleans go hand in with conditionals. If you don’t understand this concept, please ask an instructor or TA soon!

``````var isRed = [] // isRed is true if the button should
// be red, and false if the button should be green.
// We use this to determine fill color when we draw
// the buttons.

function setup() {
createCanvas(200, 40);
for (i = 0; i < 10; i++) { // there are 10 buttons
isRed[i] = false;  // all buttons start out green
}
}

function draw() {
background(255);
// draw the "click me" text
fill(0); // black text
text("click me", 10, 15);
// draw the buttons
noStroke();
for (i = 0; i < 10; i++) { // for each button...
if (isRed[i]) { // is the i'th button red?
fill(205, 0, 0); // red
} else {
fill(0, 205, 0); // green
}
// draw the i'th button at position i * 20
rect(i * 20, 20, 18, 18)
}
}

// when the mouse is pressed, toggle the isRed state
//   of the button. We have to determine which of the
//   buttons to toggle. We divide the mouse position by
//   the width of the buttons (20) to compute the button
//   number. E.g. if mouseX === 30, we're in the middle
//   of button #1 (remember the leftmost button is #0),
//   and mouseX/20 === 1.5, meaning the middle (0.5) of
//   button #1. The int() function rounds down to the
//   nearest integer, converting 1.5 into 1, which is the
//   index we are after.
//
function mousePressed() {
var index = int(mouseX / 20);
isRed[index] = ! isRed[index]; // ! means "not"
// (! true) is false, and (! false) is true
}
``````

A note about the `break` statement: In class we used something we haven’t used before. It’s called the break statement. It is extremely useful for loops because it immediately breaks out of a loop. You could put this in combination with an if statement so that, if a condition is met, you don’t need to continue with the rest of the for loop. In the case of our square button code from class, we used the break so that, once the right square is found, we don’t want to uselessly test the other squares, so we break out. This is a way to make your code more efficient.

## Strings

You’ve strings vaguely used in print statements and in text that can appear on the canvas. You’ve also learned about concatenation and the `toString`() method to convert numbers into strings. Now we’ll introduce more string methods that can allow you to search for substrings, convert them to all caps or all lowercase, and etcetera. This is super important for formatting string values and parsing data the way you want them to. It is frequently used in handling data. For example, if you gat a huge list of the 104 students by “First Name, Last Name”, you can use the string methods to change them to “Last Name, First initial”, and etcetera.

Here are a few examples of string methods. In this example, `str` is just a generic variable that holds a string value. Try running this code in setup and seeing what the statements print out. I also recommend reading the w3schools page on string methods. Remember, just like arrays, strings are zero-indexed.

```1 2 3 4 5 6 7 8 9 10 11 12 13 var str = "Hello, World!"   print (str.search("World")); print (str.search("Pie")); print (str.slice(1, 4)); print (str.substr(1, 4)); print (str.replace("Hello", "Goodbye")); print (str.toUpperCase());   var arr = str.split(" "); for (var i = 0; i < str.length; i++) { print (arr[i]); }```