1:归求斐波那契数列项
#include<stdio.h>
int f(int n);
int main()
{
int n;
scanf("%d",&n);
printf("斐波那契数列的第%d项是%d\n",n,f(n));
return 0;
}
int f(int n)
{
if(n==1||n==2){
return 1;
}else{
return (f(n-1)+f(n-2));
}
}
2:用递归求1~n的和
#include<stdio.h>
int sum(int n);
int main()
{
int n;
scanf("%d",&n);
printf("前%d项的和是%d\n",n,sum(n));
return 0;
}
int sum(int n)
{
if(n==1){
return 1;
}else{
return (sum(n-1)+n);
}
}
3:用递归求数组的前n个和
#include<stdio.h>
int sum(int arr[],int n);
int main()
{
int arr[9]={9,8,7,6,5,4,3,2,1};
int s=sum(arr,8);
printf("sum=%d\n",s);
return 0;
}
int sum(int arr[],int n)
{
if(n==0){
return arr[0];
}else{
return (sum(arr,n-1)+arr[n]);
}
}
4:用递归求数组中最大的元素
#include<stdio.h>
int max(int arr[],int n);
int main()
{
int arr[8]={1,2,3,4,5,6,8,11};
printf("%d\n",max(arr,7));
return 0;
}
int max(int arr[],int n)
{
if(n==0){
return arr[0];
}else{
if(max(arr,n-1)<arr[n]){
return arr[n];
}else{
return max(arr,n-1);
}
}
}
5:用递归和循环计算阶乘
#include<stdio.h>
long fact(int n);
long rfact(int n);
int main(void){
int num;
scanf("%d",&num);
printf("loop : %d factorial = %ld\n",num,fact(num));
printf("recursion : %d factorial = %ld\n",num,rfact(num));
return 0;
}
long fact(int n) //使用循环的函数
{
long ans;
for(ans=1;n>1;n--){
ans*=n;
}
}
long rfact(int n) //使用递归的函数
{
long ans;
if(n>0){
ans=n*rfact(n-1);
}else{
ans=1;
}
return ans;
}
6:把十进制转换成二进制可以看出递归在处理倒序时十分方便。
#include<stdio.h>
void to_binary(unsigned long n);
int main(void)
{
unsigned long num;
scanf("%ld",&num);
printf("%ld用二进制表示是",num);
to_binary(num);
return 0;
}
void to_binary(unsigned long n)
{
int r;
r=n%2;
if(n>=2){
to_binary(n/2);
}
putchar(r==0?'0':'1');
return;
}