I'm trying to calculate the expression y = (1 4 7 ... 301) / (2 5 8 ... 272) by a recursive function, but what I wrote doesn't work. Can anyone tell me what I'm not doing right? This version returns the error >Process finished with exit code -1073741571 (0xC00000FD)
here is my code
int calcSum(int start, int end, int steep){
if(start == 0){
return 0;
} else{
return start calcSum(start,end,steep);
}
}
int main() {
printf("y = %d", calcSum(1,301,3)/ calcSum(1,272,3));
return 0;
}
CodePudding user response:
The problem lies in your recursive call, you are not doing anything to make sure the function stops calling and hence it breaks. When you say you want to add numbers recursively, there are 3 things you need to do: call the same function(obviously), have a termination condition and in this case actually pass the values such that in each call it adds as per the sequence needed.
#include <stdio.h>
int calcSum(int start, int end, int steep){
// Stop calling once you have added all numbers
if(start<=end){
return start calcSum(start steep,end,steep); // increment start with steep so that in each call the next term in the sequence is added.
}
else return 0; //return 0 after start > end as we don't need to add after that.
}
int main(void) {
printf("y = %d", calcSum(1,301,3)/ calcSum(2,272,3));
return 0;
}
Here is what the working code would look like.