递归

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;
}
  1. 写一个递归函数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;
}
  1. 编写一个函数 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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值