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!
In this return statement
there is always used the array element
a[0]instead ofa[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.
And the function is called like
Though the return type of the function should be
long long intto avoid overflow.As you can see the third parameter is redundant.