# 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;
int array = 1;
int array = 2;
int array = 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;
int array = 1;
int array = 2;
int array = 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;
array = 0;
array = 1;
//...
``````

or if you want, like this:

`int[] array = new int;`

(these lines are equivalent).

Or, if you like shorthand:

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

1 Like

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

1 Like

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;  // 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 = 10;
a = 20;
b = new int;  // must size first!
b = 100;
b = 200;
c = 999;      // change a value
d = new int;  // replace with new size (empty)
e = new int[]{ 0, 1, 2, 3};  // replace with new values, different size
}
``````