函数main()在下面例子里调用函数up_and_down(),我们称这为“第一层递归”,然后up_and_down()调用自己,我们称之为“第二层递归”,第二层调用第三层,以此类推。
#include <stdio.h>
void up_and_down(int);
int main(void) {
up_and_down(1);
return 0;
}
void up_and_down(int n) {
printf("Level %d: n location %p\n", n, &n);
if (n < 4)
up_and_down(n + 1);
// this line will be executed certainly in the end in this method
printf("LEVEL %d: n location %p\n", n, &n);
}
Level 1: n location 0x0012ff48
Level 2: n location 0x0012ff3c
Level 3: n location 0x0012ff30
Level 4: n location 0x0012ff24
LEVEL 4: n location 0x0012ff24
LEVEL 3: n location 0x0012ff30
LEVEL 2: n location 0x0012ff3c
LEVEL 1: n location 0x0012ff48
递归流程
下面写一个方法,打印出一个十进制整数的二进制表示。例如二进制1101的十进制数为
1×2^3 +1×2^2 +0×2^1 +1×2^0 = 13
。
#include <stdio.h>
void to_binary(unsigned long n);
int main(void) {
unsigned long number;
printf("Enter an integer (q to quit):\n");
while (scanf("%lu", &number) == 1) {
printf("Binary equivalent: ");
to_binary(number);
putchar('\n');
printf("Enter an integer (q to quit):\n");
}
printf("Done.\n");
return 0;
}
void to_binary(unsigned long n) { /* recursive function */
int r;
r = n % 2;// 即右移>>一下,r即是移出的数
if (n >= 2)
to_binary(n / 2);
putchar(r == 0 ? '0' : '1');
return;
}
Enter an integer (q to quit):
|13
Binary equivalent: 1101
Enter an integer (q to quit):
|255
Binary equivalent: 11111111
Enter an integer (q to quit):
|1024
Binary equivalent: 10000000000
Enter an integer (q to quit):
|q
done.
斐波纳契数列:
unsigned long Fibonacci(unsigned n) {
if (n > 2)
return Fibonacci(n-1) + Fibonacci(n-2);
else
return 1;
}
网友评论