user163505 - 1 year ago 100
C Question

# C recursive function for product receiving segmentation fault

I am having difficulty with this problem. The given code is this:

#include<stdio.h>

//returns the product(5,10) = 5 * 6 * 7 * 8 * 9 * 10;

int product(int a, int b)
{
int mid;
if (a == b)
return a;
else {
mid = (a + b) / 2;
return product(a, mid) + product(mid,b);
}
}

int main() {

int p;
p = product(5,10);
printf("product is %d\n", p);

return 0;

}

The goal of this program is to multiply all the numbers in a given range, for this example, between 5 and 10 (I.E. 5 * 6 * 7 * 8 * 9 * 10). The problem uses a recursive function to do this, however in its current state the function calls itself without stopping to the point of overflowing the stack, causing the error "Segmentation fault (core dumped)". This is an assignment, so I ask that you don't give me solution but rather some tips to point me in the right direction. Thank you very much and please let me know if you need more information.

I think instead of taking the mid.You can consider doing like this too check the following code

int product(int a, int b)
{

if (a >= b)
return a;
else {

return a*product(a+1,b);
}
}

int main() {

int p;
p = product(5,10);
printf("product is %d\n", p);

return 0;

}

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download