Arrays and strings can also be processed using recursive functions. In such cases,
the function operates on a portion of the array or string during each call and
reduces the problem size by advancing an index or pointer.

For arrays, recursion is often used to process elements one at a time until all
elements have been handled. For strings, recursion can be used to compute length,
reverse a string, or perform character-based processing.
EXAMPLE:

//Sum

#include <stdio.h>

int sum(int a[], int n) {
    if (n == 0) return 0;   
    return a[0] + sum(a + 1, n - 1); 
}

int main() {
    int weights[] = {10, 20, 30};
    printf("Sum: %d", sum(weights, 3)); 
    return 0;
}
EXAMPLE:

//String Length

#include <stdio.h>

int length(char s[]) {
    if (*s == '\0') return 0;   
    return 1 + length(s + 1);  
}

int main() {
    printf("Length: %d", length("Coke"));
    return 0;
}
Previous Next