笔记(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");---->>>跳至下一空白字符
**********************************************************************************
-------一个递归的例子
#include<stdio.h>
void up_and_down(int);
int main(void)
{
}
void up_and_down(int 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
思想:
#include<stdio.h>
void to_binary(unsigned long n);
int
{
}
void to_binary(unsigned long n)
{
}
**********************************************************************************
0 0
- 笔记(3)递归思想--C Primer Plus
- 《C Primer Plus》阅读笔记(3)
- C Primer Plus - 笔记
- c primer plus笔记
- c primer plus 笔记
- 《C Primer Plus》笔记
- 【C++】《C++ Primer Plus》笔记(3)——数组
- c primer plus 笔记(1)
- 《C Primer Plus》阅读笔记(4)
- 《C Primer Plus》阅读笔记(2)
- 字符串笔记(C Primer Plus)
- c primer plus 学习笔记(1)
- 【C++】《C++ Primer Plus》笔记(1)
- c++primer plus阅读笔记(一)
- c++primer plus阅读笔记(二)
- C primer plus 第八章 例题练习(递归)
- C++Primer Plus学习笔记
- 《C Primer Plus》学习笔记
- IO流六:IO包中其他流对象
- 谁的等待,恰逢花开
- 笔记(1)一些简单的输入输出--C Primer Plus
- 笔记(2)ctype.h的字符映射函数--…
- 你的记忆为什么会不靠谱?
- 笔记(3)递归思想--C Primer Plus
- 一日小记
- 笔记(4)指针和数组--
- 笔记(5)字符串和字符串函数
- 笔记(6)存储类、链接和内存管理-…
- 笔记(7)掷骰子游戏--CPrimer
- 笔记(8)类型限定词const等
- J2EE企业应用开发知识点总结
- 电子商务商业模式实训及思考 综合文章:电商模式研究