I'm trying to solve a problem with code I found. I modified the code I found into an example I could run but I don't understand what is happening. The purpose of the code is to determine whether all of the elements of an array are identical to each other or whether there are one or more differences. It works, I just don't know how.
When all of the elements are identical to each other, the function returns 0. When they are not all identical, the function returns 1. How does this happen? What is i!=0 doing? i does not equal 0? What? Where is it getting the 1 or 0 from? I understand that the while loop is checking each element against the first element. What I don't understand is what happens next. When I delete i!=0, the function always returns 0.
bool array[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int n = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print(check(array, 30));
delay(1000);
}
int check(bool a[], int i) {
while(--i>0 && array[i]==array[0]);
return i!=0;
}