1.递归和非递归分别实现求第n个斐波那契数。
#include <stdio.h>
#include <stdlib.h>
int func1(int n)//递归
{
if (n > 2)
{
return func1(n - 1) + func1(n - 2);
}
return 1;
}
int func(int n)//非递归
{
int s1 = 1; int s2 = 1;
int s;
for (int i = 3; i <= n; i++)
{
s = s1 + s2;
s1 = s2;
s2 = s;
}
return s;
}
int main()
{
printf("%d\n", func(9));
printf("%d\n", func1(9));
system("pause");
return 0;
}
2.编写一个函数实现n^k,使用递归实现
#include <stdio.h>
#include <stdlib.h>
int factor(int n, int k)
{
if (k > 1)
{
return factor(n, k - 1)*n;
}
return n;
}
int main()
{
printf("%d\n", factor(2, 5));
system("pause");
return 0;
}
- 写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,
例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19
#include <stdio.h>
#include <stdlib.h>
int DigiSum(int n)
{
if (n > 0)
{
return n % 10 + DigiSum(n / 10);
}
return 0;
}
int main()
{
printf("%d\n", DigiSum(1729));
system("pause");
return 0;
}
- 编写一个函数 reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。
#include <stdio.h>
#include <stdlib.h>
int reverse_string(char*string)
{
if (*string != '\0')
{
reverse_string(string+1);
}
printf("%c", *(string));
}
int main()
{
char string[]="abcdef";
reverse_string(string);
printf("\n");
system("pause");
return 0;
}
5.递归和非递归分别实现strlen
#include <stdio.h>
#include <stdlib.h>
int Strlen1(char str[])//递归
{
if (str[0] == '\0')
{
return 0;
}
return 1 + Strlen1(str + 1);
}
int Strlen(char str[])//非递归
{
int size = 0;
for (int i = 0; str[i] != '\0'; i++)
{
size++;
}
return size;
}
int main()
{
char string[]="abcdef";
printf("%d\n", Strlen(string));
printf("%d\n", Strlen1(string));
system("pause");
return 0;
}
6.递归和非递归分别实现求n的阶乘
#include <stdio.h>
#include <stdlib.h>
int factor1(int n)//非递归
{
int ret = 1;
for (int i = 1; i <= n; ++i)
{
ret *= i;
}
return ret;
}
int factor2(int n)//递归
{
if (n == 1)
{
return 1;
}
return n * factor2(n - 1);
}
int main()
{
printf("%d\n", factor1(5));
printf("%d\n", factor2(5));
system("pause");
return 0;
}
7.递归方式实现打印一个整数的每一位
#include <stdio.h>
#include <stdlib.h>
int print(int n)
{
if (n > 9)
{
print(n / 10);
}
printf("%d ", n % 10);
}
int main()
{
print(1234);
printf("\n");
system("pause");
return 0;
}