Go Down

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

pempi78

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

Start from the end of the array, and work back.

pempi78

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 pm Last 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

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

Two or three hours spent thinking and reading documentation solves most programming problems.

Go Up