1) 每一级的函数调用都有自己的变量,也就是说第一级的变量n并非是第二级的变量。
int main(void)
{
up_and_down(1);
return 0;
}
void up_and_down(int n)
{
printf("Level %d: n location %p\n", n, &n); /* 1 */
if (n < 4)
up_and_down(n+1);
printf("LEVEL %d: n location %p\n", n, &n); /* 2 */
}
Level 1: n location 0x7fff5fbff8ec
Level 2: n location 0x7fff5fbff8cc
Level 3: n location 0x7fff5fbff8ac
Level 4: n location 0x7fff5fbff88c
LEVEL 4: n location 0x7fff5fbff88c
LEVEL 3: n location 0x7fff5fbff8ac
LEVEL 2: n location 0x7fff5fbff8cc
LEVEL 1: n location 0x7fff5fbff8ec
2)每一次的函数调用都会有一次返回。下一级执行到结束之后返回到上一级的函数调用处。
3)递归函数中,位于递归调用前的语句和各级调用函数都具有相同的顺序。
4)递归函数中,位于递归调用后的语句的执行顺序和各个被调用函数的顺序方相反。
5)虽然每一级递归都有自己的变量,但是函数代码并不会得到复制。
6)递归中必须包含可以终止递归调用的语句存在,否则将出现死循环。
2 .尾递归。递归调用出现在函数的尾部,即在return语句之前。
//使用 循环进行阶乘
int factor(int i)
{
int result=1,j;
for(j = 1 ;j <= i; j++)
{
result *= j;
}
return result;
}
//使用递归进行阶乘操作
int rfactor(int num)
{
int result;
if(num > 0) //递归的回归语句
result = num * rfactor(num-1);
else
result = 1;
return result;
}
//下面便是一个尾递归的例子。
int main(int argc, const char * argv[])
{
printf("please input the number:");
int num ;
scanf("%d",&num);
printf("%d \n",factor(num));
printf("%d \n",rfactor(num));
return 0;
}
3.递归和反向计算。
void Conver(int num)
{
int r = num % 2;
if(num >= 2)
Conver(num / 2);
printf("%d",r);
}
4. 使用递归的优缺点。
斐波那契数列。
1 ,1,2,3,5,8,13….