 # How to non linear iterator

Hi,

Instead of iterating through my loop with a classic iterator (when I say classic I mean iterating the loop using a fixed value with something like += 20).
I would like to iterate with a value which is increasing or decreasing as I progress through my loop iteration.

Hello @goldorak
Interesting question…

I’m not sure about details of implementation but I would start by trying to add a changing variable to the standard regular +=20.

For example: i = i + 20 + n

With the n variable being assigned a changing number via random (or other) at each iteration… Hello, @goldorak, and welcome to the Processing Forum!

Are you looking for something like this?

``````void setup() {
for (int n = 0, incr = 1; n <= 10; n += incr, incr += 1) {
println(n);
}
}
``````

Output:

``````0
1
3
6
10
``````

EDIT (July 13, 2021):

Also try this:

``````void setup() {
for (int a = 0, b = 1, c;
a <= 144;
c = a, a = b, b = c + a)
{
println(a);
}
}
``````

Does the sequence that is output look familiar?

You need to make sure the loop reaches a terminal value if the accumulative increases is close to the accmulative decreases then the loop might not end for a very long time. For instance I ran this sketch

``````int idx = 1;
for(int v = 0; v >= -100 && v <= 100; v += 5 * cos(random(TWO_PI))){
println(idx++, v);
}
``````

and it took 433954 iterations to stop but this varied a lot because of the random number. Changing it so we have `v += 5 * cos(0.75 + random(TWO_PI))` reduces it a lot because positive values predominate.

1 Like

this might be easier to understand.
You don’t have to change the actual for-loop variable i.

``````  for (int i = -110; i<111; i++) {
println(n);
float value = i*i*i;
}
``````
1 Like

Agreed, @Chrisir.

My examples were intended to answer the original poster’s query by demonstrating that the increment in a for loop can vary. The examples should have been accompanied by a caveat.

In general, the header of a loop should be a simple control structure, with the bulk of the functionality contained in the body of the loop.

The second example was inspired by this code from the official Python web site:

``````def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)
``````

As we can see, the work was performed, quite appropriately, in a while loop. But that algorithm presented an opportunity to demonstrate what could, but not necessarily what should, be done in a Java for loop header. In my example, all of the work except the output was performed in a for loop header.

So, with the caveats having been stated above, let’s carry that example to an even further extreme. Here is the loop again, with all the work contained in a header, and with no loop body at all:

``````void setup() {
for (int a = 0, b = 1, c;
a <= 144;
c = a, a = b, b = c + a, println(c));
}
``````

Caveat: don’t program in this manner. 1 Like