while I was doing a practice exercise I ran into a question, the instruction is as follows Ask for the value of X and ask for the degree of the polynomial
"Write a function of the form double polynomial(double x, double n) that recursively asks for the value of each coefficient and returns the sum of anx^n from n to 0"
I did my solution with cycles (it is the following) but I have doubts about how I could do it with recursion, I would appreciate any proposal, thanks!
for (i = 0; i <= order; i++)
{
printf("Enter coefficients of polynomial at x^%d\n", i);
scanf("%f", &coefficient[i]);
}
for (i = 0; i <= order; i++)
{
sum += coefficient[i] * pow(x, i);
}
I attach the block of code that I made with cycles, but I would like to do it with recursion
>Solution :
Write a function of the form
double polynomial(double x, double n)
is a little strange for this task. It should probably be
double polynomial(double x, unsigned n);
^^^^^^^^
I wont write the whole code but here is some pseudo code for a recursive implementation:
double polynomial(double x, unsigned n)
{
coefficient = read_nth_coefficient_from_user
if (n == 0) return coefficient
return (coefficient * (x to the power of n)) + polynomial(x, n - 1)
}
Notice the comparision n == 0 to stop recuresion and the n - 1 when doing the recursive call. These are the reason that n shall be an unsigned instead of a double
end note:
I understand that this is "a practice exercise" so fine, go ahead and use recursion. But a task like this shall not be solved using recursion in real code. A loop is much better. In general, recursion shall be avoided unless it gives you significant benefits. And when recursion is used, take care that the number of recursive calls has a well controlled (and pretty low) limit. A high number of recursive calls may lead to stack overflow. Use recursion with care.