How to find the last occurrence of a number in an array using recursion with C

1 Answer

0 votes
#include <stdio.h>

int find_last_occurrence(int arr[], int size, int num, int currentIndex) {
    if (currentIndex == size) {
        return -1;
    }

    int index = find_last_occurrence(arr, size, num, currentIndex + 1);
    
    if (index == -1 && arr[currentIndex] == num) {
        return currentIndex;
    }
    else {
        return index;
    }
}

int main()
{
    int arr[] = { 3, 9, 17, 5, 0, 3, 12, 10, 3, 15 };
    int size = sizeof(arr) / sizeof(int);
    int number = 3;

    printf("index = %d", find_last_occurrence(arr, size, number, 0));

    return 0;
}




/*
run:

index = 8

*/

 



answered May 19, 2023 by avibootz
edited May 19, 2023 by avibootz

Related questions

2 answers 228 views
1 answer 152 views
2 answers 209 views
1 answer 219 views
...