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

2 Answers

0 votes
#include <iostream>

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) {
        std::cout << "First Occurrence = " << first;
        std::cout << "\n" << "Last Occurrence = " << last;
    }
    else {
        std::cout << "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);
}
 
 
 
 
/*
run:
 
First Occurrence = 3
Last Occurrence = 9
 
*/

 

 



answered Dec 6, 2023 by avibootz
edited Dec 8, 2023 by avibootz
0 votes
#include <iostream>
#include <array>
 
template<std::size_t size>
void findFirstAndLastIndex(std::array<int, size> &arr, int element) {
    int first = -1, last = -1;
  
    for (int i = 0; i < size; i++) {
        if (arr[i] != element)
            continue;
        if (first == -1)
            first = i;
        last = i;
    }
     
    if (first != -1) {
        std::cout << "First Occurrence = " << first;
        std::cout << "\n" << "Last Occurrence = " << last;
    }
    else {
        std::cout << "Not Found";
    }
}
  
int main() {
    std::array<int, 12> arr { 3, 2, 4, 7, 3, 0, 9, 8, 7, 7, 11, 18 };
    int element = 7;
  
    findFirstAndLastIndex(arr, element);
}
  
  
  
  
/*
run:
  
First Occurrence = 3
Last Occurrence = 9
  
*/

 



answered Dec 8, 2023 by avibootz
...