I have the following code:
int array[5] = {1, 0, 1, 0, 0};
int i;
for(i = 0; i < 5; i++)
{
if(array[i] == 1)
{
printf("found one\n");
}
}
how could we know the second 1
in the array
is the last 1
we found?
I do not mean keep the value of last 1
, what I mean is how should we know the second 1
is the last occurence, no more shows up?
You can simply loop in a reverse order:
for(i = 4; i >= 0; i--)
{
if(array[i] == 1)
{
printf("last 1 found!\n");
//break or do whatever you want
}
}
We can further improve the code as follows:
int main(){
int array[] = {1, 0, 1, 0, 0}, i;
for(i=sizeof(array)/sizeof(int)-1; array[i]!=1 && --i;);
printf("last 1 found at index = %d\n", i);
return 1;
}
Codepad.
The second form of code has some additional benefits:
--i
will be performed when needed. if()
, break
).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With