Learn creative coding writing simple programs
55. How many items in an Array?
Arrays are probably used in every single program we write, so it's important to understand how they work. We can create arrays of numbers and also arrays with texts. An array is just a list of items, a collection. Instead of declaring 100 variables, we just declare one variable telling Processing that it will contain 100 different values inside.
To access each element in the array we use the square brackets with a number inside them. For example print(car_brand[22]); would print the car_brand number 22, supposing car_brand is an array that contains car brands.
To know how many items are in an array, we do print(car_brand.length); That means we add ".length" to the variable name, and this returns how many elements the array contains.
We know that when we call random(100) we get a random number between 0 and 100. But there is one important detail: we never get 100. The number we get is always smaller than 100.
Sometimes we want to use random() to choose a random element from an array. If the array has 5 elements, we can use int(random(5)) to choose the element and we will get back the integer numbers 0, 1, 2, 3 and 4, never 5, which is exactly what we want. In an array that has 5 elements, the first element is 0 and the last one is 4.
Try to stay close to the topic of this episode. Use the Processing forums for help with unrelated Processing projects (or hire me for help ;-)
To indicate that a word in your comment is code, use the `backtick`. Example
Do `float` and `int` smell similar?
To highlight code blocks, surround it with ``` code-fences ``` like this:``` void setup() { size(600, 600); } ```