I suck horribly with recursion and have never really needed to use it. I am struggling with this probably trivial issue and my brain has hit a brick wall despite having read and even watched several vids about it. What I'm thinking will happen is when someone on here corrects this error, it will "click" because I'll be able to have struggled thru an issue and now see what I was doing wrong:
Code:
#include <stdio.h>
#include <stdlib.h>
int multiply(int arr[], int size)
{
int answer;
if(size <= 1)
answer = 0;
else
answer = arr[size-1] * multiply(arr, size-1);
return answer;
}
int main()
{
int myArray[] = {5,4,3,2,1};
printf("The answer is: %d", multiply(myArray, 5));
return EXIT_SUCCESS;
}
I'm coming up with 0 here when the program is run. A couple other things I've tried: I changed the base case from answer = 0 to simply return 0, changed the base case from answer = 0 to answer = 1, and also changed the arr[size] to arr[size-1] as shown.
A couple of things I'm pondering: Am I going to low in the array (-1 somehow) and getting a 0 that way? Or perhaps since I set answer = 0, at some point, answer will always be 0. However, when I change it to answer = 1 instead, the correct answer still does not come out, instead I get a 24.
The answer should be 120. Thanks for your help. Gonna be in gdb trying to see if I can figure it out too.