I'm trying to understand recursion. Specifically there are 2 functions I can't get.
The first one is an example I came across on the Web:
#include <stdio.h>
void printnum(int begin) {
printf("%d", begin);
if (begin < 9) {
printnum(begin + 1);
}
printf("%d", begin);
}
void main() {
printnum(1);
}
The output of this function is: 123456789987654321
I can understand how it reaches from 1 to 9, however what I don't get is how it goes backwards if there's no value decrease anywhere. So how? O.o
The second function I can't get is something I came up with:
#include <stdio.h>
int dbl(int i) {
if (i == 1) {
return 1;
}
return dbl(i - 1) + dbl(i - 1);
}
void main() {
int i;
for (i = 1; i < 10; i++) {
printf("%d\t", dbl(i));
}
}
So, this one prints something like: 1 2 4 8 16 32 64 128 256
It's so confusing, there are 2 calls to the function inside the same function, and I can't understand the logic behind this. What is the exact process the function goes through to print the double of each number?
dbl(i - 1)is the result of the previous element, then you are adding the same resultdbl(i - 1). You could event writedbl(i - 1) * 2and it would work