1.请使用递归实现n!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int func(int n)
{if (n == 1){return 1;}return func(n - 1) * n;
}int main()
{int n = 5;printf("%d\n", func(5));return 0;
}
2.请使用递归实现0-n的和
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int func(int n)
{if (n == 1){return 1;}return func(n - 1) + n;
}int main()
{int n = 5;printf("%d\n", func(5));return 0;
}
3.请使用递归实现斐波那契
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int func(int n)
{if (n <= 0){return 0;}if (n == 1 || n == 2){return 1;}int a = func(n - 1) + func(n - 2);return a;
}int main()
{int n = 10;for (int i = 1; i < n; i++){printf("%4d", func(i));}puts("");return 0;
}
4.请使用递归实现二进制转换
#include <stdio.h>
#include <stdlib.h>
#include <string.h>void func(int n)
{if (n < 2){printf("%d", n);return;}func(n / 2);printf("%d", n % 2);
}int main()
{int n;scanf("%d", &n);func(n);puts("");return 0;
}
5.请递归实现计算各个位数字之和
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int func(int n)
{if (n == 0){return 0;}return n % 10 + func(n / 10);
}int main()
{int n;scanf("%d", &n);printf("%d\n", func(n));return 0;
}
6.请递归实现计算各个位数字的乘积
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int func(int n)
{if (n == 0){return 1;}return n % 10 * func(n / 10);
}int main()
{int n;scanf("%d", &n);printf("%d\n", func(n));return 0;
}
7.请使用递归实现计算单词逆置
#include <stdio.h>
#include <stdlib.h>
#include <string.h>void func(char* s, int i, int j)
{if (i >= j){return;}char t = s[i];s[i] = s[j];s[j] = t;func(s, i + 1, j - 1);
}int main()
{char s[] = "hello";int len = strlen(s) - 1;func(s, 0, len);puts(s);return 0;
}