c语言递归讲解分析

时间:2019-06-15
本文章向大家介绍c语言递归讲解分析,主要包括c语言递归讲解分析使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

C语言允许函数调用它自己,这种调用的过程称为“递归(recursion)”

举例说明,如下代码:

#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 < 3)
                up_and_down(n+1);
        printf("LEVEL %d: n location %p\n",n,&n);
}

定义一个函数up_and_down(int n),且函数当中再次调用本身。下面是程序运行效果:

[root@MiWiFi-R4-srv C]# cc recur.c

[root@MiWiFi-R4-srv C]# ./a.out
Level 1: n location 0x7ffdbc113dac
Level 2: n location 0x7ffdbc113d8c
Level 3: n location 0x7ffdbc113d6c
LEVEL 3: n location 0x7ffdbc113d6c
LEVEL 2: n location 0x7ffdbc113d8c
LEVEL 1: n location 0x7ffdbc113dac

代码分析;函数up_and_down(int n)中在包含if语句,符合条件变再次调用自身,那么可将up_and_down(int n)分解写成如下形式:

void up_and_down(int n)                                           //根据主函数赋值,n=1;
{
printf(
"Level %d: n location %p\n",n,&n);
//输出显示:Level 1 :n .............
if (n < 3) //判定n=1,且小于3;则进入if语句。 { n = n + 1; //在if语句中,n被重新赋值,且值为2。 printf("Level %d: n location %p\n",n,&n);
//输出显示:Level 2 :n .............
if (n < 3) //再次遇到if语句,n等于2,条件语句为真,则执行if语句。 { n = n + 1; //n被重新赋值,且值为3。 printf("Level %d: n location %p\n",n,&n);
//输出显示:Level 3 :n ...........
if(n < 3) //执行判定语句,条件语句为假,则跳过if语句。 up_and_down(n+1); printf("LEVEL %d: n location %p\n",n,&n); //执行语句,输出显示:LEVEL 3 :n ......... } printf("LEVEL %d: n location %p\n",n,&n); //执行语句,输出显示:LEVEL 2 :n ............ } printf("LEVEL %d: n location %p\n",n,&n); //执行语句,输出显示:LEVEL 1 :n ........ }

分析代码行为如下。

1;n 接收到主函数值为1,运行printf()函数,之后判定if语句,条件为真则继续调用本身,执行printf()函数,判定if语句。直到if条件为假,停止调用本身。

2;当 n 的值为3 时。if条件语句为假,则跳过if语句,执行printf("LEVEL %d: n location %p\n", n , &n);(注意:此时n的值为3).

3;当递归函数(n值为3时)执行结束,则将控制权返回给上一级递归(n的值为2)的时候,继续完成递归函数。重复行为,直到返回到主函数,即n的值为1的时候。

原文地址:https://www.cnblogs.com/aaron456-rgv/p/11028246.html