Reputation: 3267
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?
Upvotes: 4
Views: 311
Reputation: 95948
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;
}
The second form of code has some additional benefits:
--i
will be performed when needed. if()
, break
).Upvotes: 20
Reputation:
set a counter equal to 0 & increment it every time you find a 1. When the array is completely parsed, you will know which 1 was the last 1.
int counter = 0;
int lastone = -1;
for(i = 0; i < 5; i++)
{
if(array[i]==1)
{
counter++;
lastone = i;
printf("found one\n");
}
}
if(lastone!=-1)
printf(" %d one is the last one %d", counter, lastone);
Upvotes: 2
Reputation: 633
You can keep track of the last index where you found the "1". For example :
int array[5] = {1, 0, 1, 0, 0};
int i;
int lastIndexOf=-1;
for(i = 0; i < 5; i++)
{
if(array[i] == 1)
{
lastIndexOf=i;
printf("found one\n");
}
}
if(lastIndexOf!=-1)
printf("last index of 1 : %d\n",lastIndexOf);
Upvotes: 2