Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

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 195 views
1 answer 144 views
2 answers 193 views
1 answer 177 views
...