Using arrays inside for loops

Pretty simple question, I hope. Why does this first piece of code draw three lovely mountains, while the second does nothing?

First bit:

void setup(){
	size(800,420);  //size of mountains
}

int array[0] = 0;
int array[1] = 1;
int array[2] = 2;
int array[3] = 3;

void draw(){
	background(255);
	for(int i=0; i<3; i++){
		for(float x=1; x<width; x++){
			int a = i;
			stroke(200-a*70);  // color
			line(x,height,x,height-noise(10*i+x/width)*(height-50*i));
		}
	}
}

Second bit:

void setup(){
	size(800,420);  //size of mountains
}

int array[0] = 0;
int array[1] = 1;
int array[2] = 2;
int array[3] = 3;

void draw(){
	background(255);
	for(int i=0; i<3; i++){
		for(float x=1; x<width; x++){
			int a = array[i];
			stroke(200-a*70);  // color
			line(x,height,x,height-noise(10*i+x/width)*(height-50*i));
		}
	}
}

The difference is that in the second, I’m trying to get the same numerical values out of positions in an array.

1 Like

I don’t even know how you got the second one to compile as it is completely wrong. It does not compile on my computer. It even tells me to “Delete this”.

An array should be used like this:

int array[] = new int[4];
array[0] = 0;
array[1] = 1;
//...

or if you want, like this:

int[] array = new int[4];

(these lines are equivalent).

Or, if you like shorthand:

int[] array = {0,1,2,3};

See:
https://processing.org/reference/Array.html
https://processing.org/reference/arrayaccess.html

1 Like

Thanks very much. Thought that was a legit alternative way to set up the array, but obviously not!

2 Likes

@Focksbot:

To stay organized, first declare globals and optionally assign values at the same time (on the same line).

So you cannot do this:

int x;
x = 2; // illegal
void setup(){
  print(x);
}

…but you can assign globally at declaration, or declare, then assign later:

int x = 2;
int y;
void setup(){
  y = 4;
  print(x, y);
}

Arrays work the same way. That means you can do any of these things:

int a[] = new int[2];  // size now, values later
int b[];               // size later
int c[] = { 10, 20 };  // values now, sets the size
int d[] = { 30, 40 };
int e[] = { 40, 50 };
void setup(){
  a[0] = 10;
  a[1] = 20;
  b = new int[2];  // must size first!
  b[0] = 100;
  b[1] = 200;
  c[0] = 999;      // change a value
  d = new int[4];  // replace with new size (empty)
  e = new int[]{ 0, 1, 2, 3};  // replace with new values, different size
}