Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

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?

like image 901
user2131316 Avatar asked Nov 28 '22 08:11

user2131316


1 Answers

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).
like image 50
Maroun Avatar answered Dec 15 '22 05:12

Maroun