何为递归?
在C语言中,C允许函数调用自己,而这种调用过程称为递归。
递归的基本原理
1,每级函数调用都有自己的变量。
2,每次函数调用都会返回一次,当函数执行完毕后,控制权将被传回上一级递归,而程序也必须按照顺序去执行。
3,递归函数中位于递归调用之前的语句,均要按被调函数的顺序来执行。
4,递归函数中位于递归调用之后的语句,均按被调函数相反的顺序执行。
5,递归函数必须包含能让递归调用停止的语句。
6,递归调用十分类似于一个循环语句。
程序实例
下面的实例中,分别使用for循环以及递归计算阶乘。
#include <stdio.h>
long fact (int n);
long rfact (int n);
int main(void);
{
int num;
printf("This program calculrates factorials.\n");
printf("Enter a value in the range 0~12 (Press q to quit):\n"); //把输入限制在0~12,因为12!已经接近5亿
while(scanf("%d", &num) == 1)
{
if num < 0;
printf(“No nagative numbers,please!\n”);
else if (num < 0);
printf("Keep input under 13.\n");
else
{
printf("loop: %d factorial = %ld\n"
num, fact (num));
printf("recursion: %d factorial = %id\n"
num, rfact (num));
}
printf("Enter a value in the range 0~12(Press q to quit):\n");
}
printf("Bye Bye!\n");
return 0;
}
long fact (int n) //使用for循环
{
long ans;
for (ans = 1; n > 1; n--)
ans *= n;
return ans;
}
long rfact (int n) //使用递归
{
long ans;
if (n > 0)
ans = n * rfact(n - 1);
else
ans = 1;
return ans;
}
笔者才疏学浅,文中如有错误或疏漏,望各位读者给予指正,谢谢!