How to find the indexes of the first and last occurrences of an element in array in C

1 Answer

0 votes
#include <stdio.h>

void findFirstAndLastIndex(int array[], int size, int element) {
    int first = -1, last = -1;

    for (int i = 0; i < size; i++) {
        if (array[i] != element)
            continue;
        if (first == -1)
            first = i;
        last = i;
    }
    if (first != -1) {
        printf("First Occurrence = %d \nLast Occurrence = %d", first, last);
    }
    else {
        printf("Not Found");
    }
}

int main() {
    int array[] = { 3, 2, 4, 7, 3, 0, 9, 8, 7, 7, 12, 18 };
    int size = sizeof(array) / sizeof(array[0]);
    int element = 7;

    findFirstAndLastIndex(array, size, element);

    return 0;
}




/*
run:

First Occurrence = 3
Last Occurrence = 9

*/

 



answered Dec 6, 2023 by avibootz
edited Dec 6, 2023 by avibootz
...