How can we know that 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 to find out that the second 1 in array is the last 1 we found? I do not want to maintain the value of the last 1 , I mean, how are we to know that the second 1 is the last, is no longer displayed?

+4
source share
3 answers

You can simply loop in 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:

+20
source

You can track the last index in which you found "1". For instance:

 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); 
+2
source

set the counter to 0, and increment it every time you find 1. When the array is fully analyzed, you will know which one was the last.

 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); 
+2
source

Source: https://habr.com/ru/post/1490705/


All Articles