I’m trying to wrap my head around the for loop structure for arrays. Is there a way to assign values to the elements in the array using the array for loop structure: for(int i : arrayName)?
I’ve done this but it’s not working.
float[] cats = new float[10];
void setup() {
for (float k : cats) {
k = random(50, 100);
}
for (float i : cats) {
println(i);
}
}
If the data type is a primitive (int, float, boolean etc) or if the data type is an immutable class (Integer, Float, Boolean etc) then the answer is no.
Talking about for loops; also as a self-teaching beginner and maybe of interest to others, I recently found out that the following is possible as well.
int x = 2;
for (long y = 0, z = 4; x < 10 && y < 10; x++, y++) {
println(x+" "+y);
}
for (int x=5; x<55; x+=5) { println(x); } // step size
for (int x=100; x>=0; x--) { println(x); } // countdown
for (int x=50; x!=49; x=(x+1)%100) { println(x); } // wrap around
for (int x=0; x!=9; x+=int(random(-3,3))) { println(x); } // random walk
These may be considered bad style, however. A countdown or +2 is easy enough, but once a for loop starts to seem “fancy” it is getting hard to read, and that may be a good time to ditch it for incrementing by +1 and a count, and move the scaling / shifting inside – or turn it into a while loop to focus on a complex stopping condition.