And iterative 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);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I wrote the iterative code in a way that’s not ideal just for easier visualization. And I wrote how you usually write the functional code in one line.
The codes are doing the same thing. Only reversed. In more functional style, which is the recursive you eliminate a variable because the state is passed in each function call. In the most imperative style you need the result control variable.
What is doing in your code and calling the same function over and over again passing the value of the variable always subtracting 1, and considering the result always subtracting the value of the state of the moment, in the case represented by n
. In every flame the n
will be worth a value less until it reaches 0, when it considers only to be 1, is the output condition.
So call it:
func(5)
flame func(4) - 5
what call func(3) - 4
what call func(2) - 3
what call func(1) - 2
what call func(0) - 1
and then how func()
receives 0 he falls in the other condition and returns 1 without calling anything else. Note that it will form a function call stack (the term officially used is this same).
There on the return of the call from func(1) - 2
is -1, since func(0)
we know it is 1. And the return of this is -2, and the return of the next is -3, and then returns -4, and finally returns -5. If you accumulate all this you will have -14.
My suggestion to better understand is to see running, put this code to run in an IDE, turn on a breakpoint, Stop at the first line and go running step by step, and see how everything is called, how the values are changing. There is no better way to understand the functioning of the computer in the algorithm that is trying to identify what it does.
I made an answer about recursion in Python, Determine the nth Fibonacci term with recursion, see if it helps you with anything.
– Woss