I understand the concept of recursion and how it stacks up with each call. But I fail to explain how recursive calls are working and gets printed when there are two function call separated by a printf command. Can anyone explain to me how this recursive call is working?
I have found an example regarding a game called "Towers of Hanoi". Ut was used as an example of recursion. The code:
#include <stdio.h>
void transfer(int n, char from, char to, char temp);
int main()
{
int n;
printf("how many disk");
scanf("%d", &n);
printf("\n");
transfer(n, 'L', 'R', 'C');
return 0;
}
/*
* n = number of disk,
* from = origin,
* to = destination,
* temp = temporary storage
*/
void transfer(int n, char from, char to, char temp)
{
if (n > 0) {
// Move n-1 disks from origin to temporary
transfer(n - 1, from, temp, to);
// Move n th disk from origin to destination
printf("move disk %d from %c to %c\n", n, from, to);
// Move n-1 disks from temporary to destination
transfer(n - 1, temp, to, from);
}
}
for n=3
it gives output like this
move disk 1 from L to R // move disk 2 from L to C // move disk 1 from R to C // move disk 3 from L to R // move disk 1 form C to L // move disk 2 from C to R // move disk 1 from L to R //