#include <stdio.h>
void findFirstAndLastOccurrence(int arr[], int n, int target, int *first, int *last) {
*first = -1;
*last = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
if (*first == -1) {
*first = i; // record first occurrence
}
*last = i; // update last occurrence
}
}
}
int main() {
int arr[] = {1, 2, 3, 2, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 2;
int first, last;
findFirstAndLastOccurrence(arr, n, target, &first, &last);
printf("First occurrence of %d is at index: %d\n", target, first);
printf("Last occurrence of %d is at index: %d\n", target, last);
return 0;
}
for (int i = 0; i < n; i++) {
iterate through each element in the array
check if current element matches the target
if first occurrence not set, set it now
*first = i; // record first occurrence
record index of first occurrence
*last = i; // update last occurrence
update last occurrence index to current
First occurrence of 2 is at index: 1
Last occurrence of 2 is at index: 5