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

1 Answer

0 votes
#include <stdio.h>

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

    if (arr[currentIndex] == num) {
        return currentIndex;
    }

    return find_first_occurrence(arr, size, num, currentIndex + 1);
}

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

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

    return 0;
}




/*
run:

index = 5

*/

 



answered May 19, 2023 by avibootz

Related questions

2 answers 227 views
1 answer 161 views
2 answers 209 views
1 answer 219 views
...