递归的基本概念与递归程序设计以及常见的递归算法
#include <stdio.h>
// 1. 求n!
int fact(int n)
{
if(n <= 1)
return 1;
return n * fact(n-1);
}
// 2.Fibonacci数列,前两项为1,第三项开始每项等于前两项的和
int fibonacci(int n)
{
if(n == 1 || n == 2)
return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
// 3.打印数字三角形
void print(int n)
{
if(n > 0)
{
print(n-1);
for (int i = 1; i <= n; ++i)
printf("%d ",n);
printf("\n");
}
}
// 4. 递归求数组的最大值
int max(int a[], int left, int right)
{
int lMax, rMax, mid;
if(left == right)
return a[left];
else
{
mid = (left+right)/2;
lMax = max(a,left,mid);
rMax = max(a,mid+1,right);
return lMax > rMax ? lMax : rMax;
}
}
int main()
{
int n = 5;
printf("%d! = %d\n",n,fact(n));
printf("fibonacci数列的第%d项为%d\n",n,fibonacci(n));
print(5);
int a[10] = {1,2,3,4,5,11,7,8,9,10};
printf("数组最大的数是:%d", max(a,0,9));
return 0;
}
评论 (0)