How to find the last occurrence of a character in a string using recursion with C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

int find_last_occurrence(char str[], size_t size, char ch, int currentIndex) {
    if (currentIndex == size) {
        return -1;
    }

    int index = find_last_occurrence(str, size, ch, currentIndex + 1);

    if (index == -1 && str[currentIndex] == ch) {
        return currentIndex;
    }
    else {
        return index;
    }
}

int main()
{
    char str[] = "c c++ java c# rust python";
    size_t size = strlen(str);
    char ch = 'c';

    printf("index = %d", find_last_occurrence(str, size, ch, 0));

    return 0;
}




/*
run:

index = 11

*/

 



answered May 19, 2023 by avibootz

Related questions

1 answer 161 views
1 answer 136 views
2 answers 193 views
1 answer 167 views
1 answer 160 views
...