I have this code:
#include <stdio.h>
#include <stdlib.h>
int func(int n0, int n);
int main ()
{
int n0, n, nFinal=0;
printf ("Enter constant (n0): ");
scanf ("%d", &n0);
printf ("Enter the number of iteractions (n): ");
scanf ("%d", &n);
nFinal = func(n0, n);
printf ("nFinal after %d iteractions is %d: \n", n, nFinal);
return 0;
}
int func(int n0, int n){
int i,nFinal=0;
for (i = 0; i < n; i++){
nFinal = (nFinal*nFinal) + n0;
}
return nFinal;
}
The nFinal is calculated within a for loop. I would like to achieve the same result but doing a recursive function.
From what I see, I cannot change the function call because I always need the start number and the number of iterations. Therefore, after the first iteration, the program would have to call again nFinal = func (n0, n); but as I need at each iteration of the calculated value of nFinal, I will have to change this.
Is it possible to make a recursive function but maintaining the function as nFinal = func (n0, n);?
Can someone point me some way?
Looking at your function
If n is (less than) 0, your result is 0. Then the new value of nFinal is the old value of nFinal^2 + n0, so you get: