程序调用自身的编程技巧称为递归( recursion)。递归做为一种算法在程序设计语言中广泛应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。
在学习C语言的时候,递归也作为一个重要的角色出现在我们的视野中。
在递归的案例中,斐波那契数是一个很经典的例题,在前面已经为大家总结(C语言实现斐波那契数列点击打开链接)。在此也为大家附上其它的练习:
1、编写一个函数求n的阶乘:
- //递归
- #include<stdio.h>
- #include<string.h>
- #include<assert.h>
- int fa(int n)
- {
- if (n <= 1)
- {
- return 1;
- }
- else
- {
- return n*fa(n - 1);
- }
- }
- int main()
- {
- int n = 5;
- int ret = fa(n);
- printf("ret = %d\n", ret);
- system("pause");
- return 0;
- }
- #include<stdio.h>
- #include<string.h>
- //#include<assert.h>
- void print(int n)
- {
- if (n > 9)
- {
- print(n / 10);
- }
- printf("%d\n", n % 10);
- }
- int main()
- {
- print(1234);
- system("pause");
- return 0;
- }
- #include<stdio.h>
- int pow(int n, int k)
- {
- if (k == 0)
- {
- return 1;
- }
- else if (k == 1)
- {
- return n;
- }
- else
- {
- return n*pow(n, k-1 );
- }
- }
- int main()
- {
- int n = 2;
- int k = 3;
- printf("%d\n", pow(n, k));
- system("pause");
- return 0;
- }
- #include<stdio.h>
- #include<assert.h>
- int my_strlen_no(char const *p)
- {
- assert(p != NULL);
- if (*p == NULL)
- {
- return 0;
- }
- else
- {
- return (1 + my_strlen_no(p + 1));
- }
- }
- int main()
- {
- char *p = "abcdef";
- printf("长度是:%d\n", my_strlen_no(p));
- system("pause");
- return 0;
- }
- #include<stdio.h>
- void reserve_string(char *string)
- {
- if (*string == '\0')
- printf("%c", *string);
- else
- {
- reserve_string(++string);//输入下一个字符
- printf("%c", *(--string));
- }
- }
- int main()
- {
- char s[] = "abcdef";
- reserve_string(s);
- system("pause");
- return 0;
- }
- #include<stdio.h>
- int dig(int n)
- {
- if (n <= 10)
- {
- return 1;
- }
- else
- {
- return (n % 10 + dig(n / 10));
- }
- }
- int main()
- {
- printf("%d\n", dig(1729));
- system("pause");
- return 0;
- }