user2131316
user2131316

Reputation: 3267

how could we know this is the last element in the array?

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

Answers (3)

Maroun
Maroun

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;
}

Codepad.

The second form of code has some additional benefits:

  • Include initialization.
  • Size independence of array.
  • Fast in two ways: Short-circuit behavior of &&, --i will be performed when needed.
  • Smaller code (removed if(), break).

Upvotes: 20

user2560622
user2560622

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

Alex Barac
Alex Barac

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

Related Questions