Home > Blockchain >  How do I write a C program to calculate length of an array using recursion
How do I write a C program to calculate length of an array using recursion

Time:12-18

I am trying to write a recursive program to find length of array in C language .

although i have seen solutions in python but i couldn't apply them in C.

I wrote a piece of code:

int elementcounter(int *arr, int n)
{   
    if(arr[n] == '\0')
    {
        return 0;
    }
    else
    {
     
        return ( 1 elementcounter(arr, (n 1)));
    }


}

But it is not giving correct answers. i have printed it by:

printf("the total elements are %d\n", (elementcounter(arr, 0)-1));

CodePudding user response:

When passing an array to a function, without being told how many elements there are in the arry, the only way for the function to not walk off the end of the array is if there is a special (and extra) sentinel value marking the end of the array.

I've revised your code somewhat and added some extra.

#include <stdio.h>
#include <limits.h>

#define SENTINEL INT_MIN // an unlikely but not impossible integer value

int elementcounter( int *arr, int n ) {
    return arr[n] == SENTINEL ? 0 : 1   elementcounter( arr, n 1 );
}

int main() {
    int arr[] = { 42, 0, 23, 1024, -57, 45678, SENTINEL };

    int n = elementcounter( arr, 0 );

    printf( "# of elements: %d\n(%d really when accounting for the terminator.)\n", n, n 1 );

    printf( "The compiler says there are %d elements in this array.\n", sizeof arr / sizeof arr[0] );

    return 0;
}
# of elements: 6
(7 really when accounting for the terminator.)
The compiler says there are 7 elements in this array.

Changing the "bottom of the recursion" return value from 0 to 1 means that the function DOES correctly count the sentinel element, too. It is part of the array.

EDIT:
Here is an iterative code snippet that doesn't thrash the stack with recursion. The simplest solution is the best solution.

    int n = 0;
    while( arr[n] != SENTINEL ) n  ;
    n  ; // the uncounted sentinel element

    printf( "# of elements: %d\n", n );

CodePudding user response:

This can only be done if you have a specific array-terminator element, like the string null-terminator. This is because once you pass an array to a function all you're left with is a pointer. And it's only a pointer to a single value.

If you have a terminator element, then just check for it and if not found call recursively with the index plus one. If the terminator is found return 0, otherwise return 1 plus the result of the recursive call.

If there is no terminator element in your array, then it's impossible and can't be done using recursion or plain loops.

Also note that unless coded with tail-recursion in mind, and the compiler actually doing tail-recursion, you could risk a stack overflow if the array is too long leading to a too deep recursion.

  • Related