Why backwards-for-loops don't work?


How come a for-loop can’t run backwards?

I sometimes need to run backwards through arrays and wanted something shorter than a while loop and reverse() doesnt seem to work for higher-D arrays e.g. reverse(array)

Have tried in a few sketches and never works - the code just gets ignored completely - doesn’t even error.

Have tried googling and found advice telling people to reverse arrays but never the underlying reason why?

eg using the fft example code

import processing.sound.*;

FFT fft;
AudioIn in;
int bands = 128;
float[] spectrum = new float[bands];

void setup() {
  size(512, 360);
  // Create an Input stream which is routed into the Amplitude analyzer
  fft = new FFT(this, bands);
  in = new AudioIn(this, 0);
    // start the Audio Input
    // patch the AudioIn

void draw() { 

//backwards for loop - doesnt work
for(int i = bands-1; i < 0; i--){
line( i, height, i, height - spectrum[i]*height*5 );
//more manual backwards loop - does work
//int j = bands-1;
//line( j, height, j, height - spectrum[j]*height*5 );


Seems to just be a thing but was curious as to the reasons why

Thank you kindly

1 Like

I think it should be

Original version never starts because i (128-1) is not smaller than zero.


If you want to include element[0] then it should be

for(int i = bands-1; i >= 0; i--){
1 Like

many thanks for that - works now :slight_smile:

I was thinking the conditional was an until statement when it should a while statement
(even though looking at a forwards loop example should have clued me in - just didnt make the connect!)

Thanks muchly - I’ll give it a go :slight_smile:

Yep, and funnily enough it defaults to true, so if you want while (true) you can also write for (;;), should you wish to save a few characters, as well as confuse a few characters! :smile: