递归实现一些简单程序

1.递归和非递归分别实现求第n个斐波那契数。 
#include<stdio.h>//1 1 2 3 5 8 13 21 .....
#include<stdlib.h>
int fib1(int X)
{
	if(X<=2)
	return 1;
	else
	return fib1(X-1)+fib1(X-2);
}
int fib2(int Y)
{
	int n1=1;
	int n2=1;
	int n3=0;
	int i=0;
	if(Y<=2)
	return 1;
	for(i=0;i<Y-2;i++)
	{
		n3=n1+n2;
		n1=n2;
		n2=n3;
	}
	return n2; 
}
int main()
{
	int x=0;
	int ret1=0;
	int ret2=0;
	scanf("%d",&x);//想要求斐波那契的位数
	ret1=fib1(x);
	printf("%d\n",ret1);
	ret2=fib2(x);
	printf("%d\n",ret2);
	system("pause");
	return 0;
}


2.编写一个函数实现n^k,使用递归实现 

#include<stdio.h>//n的k次方
#include<stdlib.h>
int Mi(int n,int k)
{
	if(k <= 0)
	{
		return 1;
	}
	else
		return n*Mi(n,k-1);
}
int main()
{
	int n = 0;
	int k = 0;
	int ret = 0;
	scanf("%d %d",&n,&k);
	ret=Mi(n,k);
	printf("%d",ret);
	system("pause");
	return 0;
}


3. 写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19 

#include<stdio.h>
#include<stdlib.h>
int DigitSum(int n)
{
	static int sum = 0;
	if(n>9)
	{
		DigitSum(n/10);
	}
	sum=sum+n%10;
	return sum;
}
int main()
{
	int n = 1729;
	int ret = 0;
	ret = DigitSum(n);
	printf("%d\n",ret);
	system("pause");
	return 0;
}


4. 编写一个函数reverse_string(char * string)(递归实现) 
实现:将参数字符串中的字符反向排列。 
要求:不能使用C函数库中 
的字符串操作函数。 

#include<stdio.h>
#include<stdlib.h>
void reverse_string(char * arr)
{
	if(*arr=='\0')
	{
		printf("%c\n",*arr);
	}
	else
	{
		reverse_string(++arr);
		printf("%c\n",*(--arr));
	}
}
int main()
{
	char arr[]="abcd1234";
	reverse_string(arr);
	system("pause");
	return 0;
}


5.递归和非递归分别实现strlen 
#include<stdio.h>
#include<stdlib.h>
int strlen1(char *arr)//递归
{
	if(*arr=='\0')
	{
		return 0;
	}
	else
	return 1+strlen1(arr+1);
}
int strlen2(char *arr)
{
	int count = 0;
	while(*arr!='\0')
	{
		arr++;
		count++;
	}
	return count;
}
int main()
{
	char arr[]="abcd12345";
	int ret1 = 0;
	int ret2 = 0;
	ret1=strlen1(arr);
	ret2=strlen2(arr);
	printf("%d\n",ret1);
	printf("%d\n",ret2);
	system("pause");
	return 0;
}


6.递归和非递归分别实现求n的阶乘 
#include<stdio.h>
#include<stdlib.h>
int factorial1(int n)//递归
{
	if(n<=1)
	{
		return 1;
	}
	else
		return n*factorial1(n-1);
}
int factorial2(int n)
{
	int x = 1;
	if(n<=1)
	{
		return 1;
	}
	else
	{
		int i = 0;
		for(i=1;i<=n;i++)
		{
			x=x*i;
		}
	}
	return x;
}
int main()
{
	int n = 0;
	int result1 = 0;
	int result2 = 0;
	scanf("%d",&n);
	result1 = factorial1(n);
	printf("%d\n",result1);
	result2 = factorial2(n);
	printf("%d\n",result2);
	system("pause");
	return 0;
}


7.递归方式实现打印一个整数的每一位
#include<stdio.h>
#include<stdlib.h>
void print(int X)
{
	if(X>9)
	{
		print(X/10);
	}
	printf("%d ",X%10);
}
int main()
{
	int x=1234;
	print(x);
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值