笔记(3)递归思想--C Primer Plus

来源:互联网 发布:手机导航软件 编辑:程序博客网 时间:2024/06/06 11:41
**********************************************************************************
-------一个递归的例子

#include<stdio.h>
void up_and_down(int);
int main(void)
{
    up_and_down(1);
     return0;
}

void up_and_down(int n)
{
     printf("Level %d: n location %p\n",n,&n);
      if(n<5)
        up_and_down(n+1);
     printf("LEVEL %d: n location%p\n",n,&n);

}
运行结果:
Level 1: n location 0012F8F8
Level 2: n location 0012F820
Level 3: n location 0012F748
Level 4: n location 0012F670
Level 5: n location 0012F598
LEVEL 5: n location 0012F598
LEVEL 4: n location 0012F670
LEVEL 3: n location 0012F748
LEVEL 2: n location 0012F820
LEVEL 1: n location 0012F8F8
思想:
  一、可以看出每一级的递归都使用它自己私有的变量n
 亦即第一级调用中的n不同于第二级调用中的n,虽然变量名字都是n,但它们分别具有不同的值
 二、程序执行到某一级递归结尾会转移到第1级,程序不能直接返回main()中的初始部分,
  而是通过递归的每一级的返回即从up_and_down()的某一级递归返回到调用它的那一级。
  三、递归调用前第1级、第2级、第3级、第4级、第5级
     递归调用后第5级、第4级、第3级、第2级、第1级
 四、虽每一级都有自己的变量(较多级是耗内存),但函数代码并不会得到复制,递归调用非常类似于一个循环语句。
     
    


   另一个递归的例子---十进制数转化为二进制输出

#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("%ul",&number))
    {
    printf("Binary equivalent: ");
    to_binary(number);
    printf("\n");
    printf("Enter an integer(q to quit):\n");
    }
    return0;
}
void to_binary(unsigned long n)
{
   int r;
   r=n%2;
   if(n>=2)
     to_binary(n/2);
  putchar('0'+r);   //越早得到越晚输出--递归实现

   return;
}


 scanf("%*s");---->>>跳至下一空白字符


**********************************************************************************
0 0
原创粉丝点击