new coder
new coder

Reputation: 19

Searching for values in array

i'm new to coding and have been introduced to C language. I need help understanding a specific concept.

I want to know how I can search for a specific number(e.g. 4) in a array(e.g. {1 2 4 5 6 4 6}). How ever I want to print out the index of the last occurrence of 4. How can I do this?

I have managed to so far do this...What i don't understand is how to show the ''last occurrence of a given number''

#include <stdio.h>
LastIndexOf(int search, int values[], int numValues){
    int i;
    int display;
    for(i=0;i<numValues;i++){
        if(values[i] == search){
            display = i
        }
    }
}

any help would be much appreciated.

Upvotes: 0

Views: 127

Answers (1)

mosh442
mosh442

Reputation: 738

Something like this should work

#include <stdio.h>
int LastIndexOf(int search, int values[], int numValues){
    int i;
    int display=-1;
    for(i=0;i<numValues;i++){
        if(values[i] == search){
            display = i;
        }
    }
    return display;
}

void main() {
    int display = LastIndexOf( ... );
    printf("Last occurrence at postion %i \n",display);
    return 0;
}

As suggested in the comments, the version going backwards is far better:

int LastIndexOf(int search, int values[], int numValues){
   for(int i=numValues-1;i>=0;i--){
       if(values[i] == search) {
            return  i;
       }
   }
   return -1;
}

Upvotes: 4

Related Questions