Storing Mouse Data

Example from the Processing book, page 307

```int[] y;

void setup() {
size (100,100);
y = new int[width];
}

void draw() {
background(204);
// Shift the values to the right
for (int i = y.length - 1; i > 0; i--) {
y[i] = y[i-1];
}
// Add new values to the beginning
y = constrain(mouseY, 0, height-1);
// Display each pair of values as a line
for (int i = 1; i < y.length; i++) {
line(i, y[i], i-1, y[i-1]);
}
}
```

Two questions for the reader to check if you understand the code here

• In the second for loop we start counting from int i = 1; In other examples where we iterate through an arary the for loop start with 0.
• Question: Why do we start at 1 here?
• The first for loop iterates through the arary backwards. We start at int i = y.length - 1; and each loop we decrement (i--) until we reach 1 (i > 0;)
• Question: Why do we have to loop through the array backwards in this case?
page revision: 0, last edited: 03 Dec 2009 11:21
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License