Go Down

### Topic: Extracting Last number of array that is not a zero (Read 298 times)previous topic - next topic

#### pempi78

##### May 13, 2018, 05:04 pm
Hi there i'm basically stuck trying to get the last number out of an array that is not a 0 so in this case 6. Can this be done? thanks for any help!!

Code: [Select]
`int myArray[10]={3, 8, 5, 6, 9, 2, 5, 6, 0, 0};int lastNumber;void setup() { Serial.begin(115200);  }void loop() { for (int i = 0; i < 9; i++)  lastNumber = myArray[i]; Serial.println(lastNumber); }`

#### TolpuddleSartre

#1
##### May 13, 2018, 05:06 pm
Start from the end of the array, and work back.

#### pempi78

#2
##### May 13, 2018, 05:25 pm
Start from the end of the array, and work back.
yeah i figured that but i have tried with no luck
Code: [Select]
`int myArray[10]={3, 8, 5, 6, 9, 2, 5, 6, 0, 0};int lastNumber;void setup() { Serial.begin(115200);  }void loop() { for (int i = 9; i < 9; i--) if(i > 0){      lastNumber = i;          }   Serial.println(lastNumber); }`

#### TolpuddleSartre

#3
##### May 13, 2018, 05:27 pmLast Edit: May 13, 2018, 05:28 pm by TolpuddleSartre
Luck isn't required.
Code: [Select]
`int myArray[10]={3, 8, 5, 6, 9, 2, 5, 6, 0, 0};int lastNumber;void setup() { Serial.begin(115200);}void loop() { for (lastNumber = 9; lastNumber >= 0 && myArray [lastNumber] == 0; lastNumber--) { } Serial.println(myArray [lastNumber]); }`
I haven't compiled or tested this.

#### pempi78

#4
##### May 13, 2018, 05:31 pm
Luck isn't required.
Code: [Select]
`int myArray[10]={3, 8, 5, 6, 9, 2, 5, 6, 0, 0};int lastNumber;void setup() { Serial.begin(115200);}void loop() { for (lastNumber = 9; lastNumber >= 0 && myArray [lastNumber] == 0; lastNumber--) { } Serial.println(myArray [lastNumber]); }`
I haven't compiled or tested this.
Wow it works!!! Thankyou very much!!!!

#### Robin2

#5
##### May 13, 2018, 05:37 pm
Two or three hours spent thinking and reading documentation solves most programming problems.

Go Up