And iterative do you understand?
#include <stdio.h>
int func(int n) {
return n == 0 ? 1 : func(n - 1) - n;
}
int main() {
int a;
printf("Digite um valor inteiro: ");
scanf("%d", &a);
printf("%d\n", func(a));
//agora iterativo
int n = a;
int temp = 1;
while (1) {
temp -= n; //faz a acumulação na mão
n--; //faz o n - 1 guardando seu próprio estado
if (n == 0) break; //condição de saída, poderia estar no próprio while com condição invertida
}
printf("%d\n", temp);
}
See running on ideone . And no Coding Ground . Also put it on GitHub for future reference .
I wrote the iterative code in a way that is not ideal just to visualize it easier. And I wrote down how you write the functional code in just one line.
The codes are doing the same thing. Only in an inverted way. In more functional style, which is the recursive you delete a variable because the state is being passed in each function call. In the most imperative style you need the result control variable.
What you are doing in your code and calling the same function one after another passing the value of the variable always subtracting 1, and considering the result always subtracting the value of the moment state, in the case represented by n
. In each flame the n
will value a value less until it reaches 0, when it considers only to be 1, it is the output condition.
Then call this:
func(5)
calls func(4) - 5
calling func(3) - 4
calling func(2) - 3
calling func(1) - 2
calling func(0) - 1
and then func()
receiving it falling into the other condition and returning 1 without calling anything else . Note that it will form a stack of function calls (the term officially used is this one).
Then in the return of the call of func(1) - 2
is -1, since func(0)
we know that it is 1. And the return of this is -2, and the return of the following is -3, and then returns -4, and finally returns -5. If you accumulate all this it will have -14.
My suggestion to understand better is to see running, put this code to run in an IDE, call a breakpoint , stop in the first line and go running step by step, and see how everything is going called, as the values change. There is no better way to understand how the computer works in the algorithm that is trying to identify what it does.