Why does the following base case for recursion in C not work?

47 Views Asked by At

I am practicing recursion function in C. The question is to create a recursive function to print a sum of all of the elements (int) in an array without changing the main function.

I know how to write the base case with

int recursive(int a[], int size, int i) {
  if (i>=size){
    return 0; 
  }
  return a[i] + recursive(a, size, i+1); 
}

However, I was wondering why the base case for the following code does not work.

#include <stdio.h> 

int recursive(int a[], int size, int i) {
  if (i==size-1){
    return a[size-1]; 
  }
  return a[0] + recursive(a, size, i+1); 
}

int main(void) {

  int arrSize;

  printf("Please enter the size of the array: ");

  scanf("%d", &arrSize);

  int arr[arrSize];

  printf("Please enter the elements of the array: ");

  for (int i = 0; i < arrSize; i++)
    scanf("%d", &arr[i]);
    
  int result = recursive(arr, arrSize, 0);

  printf("The result is %d.\n", result);

  return 0;

}

Thank you for reading!

1

There are 1 best solutions below

3
Vlad from Moscow On BEST ANSWER

In this return statement

return a[0] + recursive(a, size, i+1);

there is always used the array element a[0] instead of a[i]

Also even the first recursive function is unsafe due to the types of its parameneters and the presence of the third parameter.

The function can be defined the following way.

int recursive( const int a[], size_t size ) 
{
    return size == 0 ? 0 : a[0] + recursive( a + 1, size - 1 );
}

And the function is called like

int result = recursive(arr, arrSize);

printf("The result is %d.\n", result);

Though the return type of the function should be long long int to avoid overflow.

As you can see the third parameter is redundant.