Reputation: 5
I have a problem with for loops and an array in Arduino IDE.
How can I get test1 to work?
void test1(){
for(int i=1; i<5; i++) {
individualPixels[i]==1;
}
}
void test2(){
individualPixels[1]=1;
individualPixels[2]=1;
individualPixels[3]=1;
individualPixels[4]=1;
}
}
void test3(){
for(int i=1; i<5; i++) {
Serial.println(individualPixels[i]); //prints out 0 4 times
}
}
Upvotes: 0
Views: 4935
Reputation: 5
Thanks very much to all of you. I have a large array with 60 indexes and want to set some of them 1 with a for loop. The "==" was the main problem. It's working now like I want it to:
void test1(){
for(int i=1; i<5; i++) {
individualPixels[i]=1;
}
}
void test2(){
individualPixels[1]=1;
individualPixels[2]=1;
individualPixels[3]=1;
individualPixels[4]=1;
}
void test3(){
for(int i=1; i<5; i++) {
Serial.println(individualPixels[i]); //prints out 0 4 times
}
}
Upvotes: 0
Reputation: 804
You're not actually assigning anything in test1, you're testing
for equality (individualPixels[i]==1
should be individualPixels[i] = 1
, note the single equality sign).
Also, as other commenters mentioned, C/C++ uses zero based indexing.
Upvotes: 1
Reputation: 174
The for loops start with i = 1 that should be 0 as an element in an array can be accessed with an index from 0 to size-1. An array with 4 elements can be accessed as follows:
array[0] --- first element
array[1] --- second element
array[2] --- third element
array[3] --- fourth element
Apart from that, the first for loop (that doesn't work) used the == operator, which checks if two variables are equal and then returns a boolean as a result. Instead you should use a single = that will set the value.
The second test has an extra } ,which should be removed
I suggest you to start actually learning programming, for example by reading a (e)book, as you will teach yourself bad habits (accessing arrays in a wrong way), which may work, but may not be efficient.
Upvotes: 1
Reputation: 4872
C/C++ uses zero indexed arrays, so your for
loops in test1 and test3 should look like this:
for(int i=0; i<4; i++) {
individualPixels[i]==1;
}
Test2 has an unmatched bracket and the array indexes should start at zero:
void test2(){
individualPixels[0]=1;
individualPixels[1]=1;
individualPixels[2]=1;
individualPixels[3]=1;
//} this shouldn't be here
}
Upvotes: 1