找了一些递归算法的题目练习:
- 递归和非递归分别实现求第n个斐波那契数。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int Fibonacci( int num) {
if (num ==1||num==2) {
return 1;
}
else
return Fibonacci(num - 1)+Fibonacci(num-2);
}
int main (){
long long a, result=1,temp=1;
scanf("%ld", &a);
//result = Fibonacci(a);//使用递归的算法
for (int i = a-2; i > 0;--i) {//不使用递归的算法,由于前两个数已经给出,所以循环次数比实际值要小2;
result = result + temp;
temp = result - temp;//temp中保存result之前的值
}
printf("%d\n", result);
system("pause");
return 0;
}
- 编写一个函数实现n^k,使用递归实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int power(int a, int b) {
if (b > 0) {
return a*power(a, b - 1);
}
else {
return 1;
}
}
int main (){
int n, k;
printf("please enter a num:");
scanf("%d", &n);
printf("please enter another num:");
scanf("%d", &k);
printf("n^k=%d\n",power(n,k));
system("pause");
return 0;
}
- 写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,
例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int fun(int source) {
int tmp=source;
if(tmp>=10){
return tmp%10+fun(tmp / 10);
}
else{
return source;
}
}
int main (){
int num;
printf("please enter a num:");
scanf("%d", &num);
printf("%d",fun(num));
system("pause");
return 0;
}
- 编写一个函数 reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* reverse_diy(char* soure) {
if (*soure != '\0') {
char temp;
unsigned int len = strlen(soure) - 1;
temp = soure[0];
soure[0] = soure[len];
soure[len] = '\0';
reverse_diy(soure + 1);
soure[len] = temp;
}
return soure;
}
int main (){
char str[] = "kishere";
reverse_diy(str);
printf("%s\n", str);
system("pause");
return 0;
}```
5. 递归和非递归分别实现strlen
```c
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
unsigned int strlens(char* str) {
if (*str!='\0'){
return 1+strlens(str + 1);
}
else {
return 0;
}
}
int main (){
char str[] = { "kishere" };
unsigned int len=strlens(str);
printf("the lenth of str =%d\n",len);
system("pause");
return 0;
}
- 递归和非递归分别实现求n的阶乘
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int fun(int a){
if (a==1){
return 1;
}
else{
return a*fun(a-1);
}
}
int main(){
int a;
scanf("%d",&a);
printf("%d\n",fun(a));
system("pause");
return 0;
}
- 递归方式实现打印一个整数的每一位
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int fun(int a) {
if (a<10){
printf("%d", a);
return 0;
}
else {
printf("%d", a % 10);
return fun(a / 10);
}
}
int main (){
int num;
scanf("%d", &num);
fun(num);
system("pause");
return 0;
}