1.递归和非递归分别实现求第n个斐波那契数。
#include <stdio.h> #include <Windows.h> int getFib(int n) { int first = 1; int second = 1; int third = 1; while (n > 2) { third = first + second; first = second; second = third; n--; } return third; } int fib(int n) { //递归 if (n <= 2) return 1; else return fib(n - 1) + fib(n - 2); } int main() { int ret = getFib(4); int _ret = fib(4); printf("%d\n%d\n", ret, _ret); system("pause"); return 0; }
2.编写一个函数实现n^k,使用递归实现
#include <stdio.h> #include <Windows.h> //实现 n ^ k; int _power(int n, int k) { if (k == 0) return 1; else return n * _power(n,k - 1); } int main() { int ret = _power(2, 3); printf("%d\n", ret); system("pause"); return 0; }
3. 写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19
#include <stdio.h> #include <Windows.h> int DigitSum(int n) { if (n == 0) return 0; else return (n % 10) + DigitSum(n / 10); } int main() { int n; printf("请输入一个正整数:\n"); scanf_s("%d", &n); int ret = DigitSum(n); printf("%d\n", ret); system("pause"); return 0; }4. 编写一个函数reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。
#include <stdio.h> #include <windows.h> char * reverse_string(char *p){ int n = 0; char temp; char *q; //用q保存开始的p q = p; while (*p != 0){ //计算出字符串的大小 n++; p++; } if (n > 1){ temp = q[0]; q[0] = q[n - 1]; q[n - 1] = '\0'; reverse_string(q + 1); q[n - 1] = temp; } return q; } int main() { char str[] = "i love u forever"; printf("原字符串是:%s\n", str); printf("翻转后的字符串是:%s\n", reverse_string(str)); system("pause"); return 0; }
5.递归和非递归分别实现strlen
#include <stdio.h> #include <windows.h> #include <assert.h> int my_strlen_two(const char* str){ //递归实现 assert(str != NULL); if (*str) return 1 + my_strlen_two(str + 1); else return 0; } int my_strlen_one(const char* str){ //非递归实现 int count = 0; assert(str != NULL); while (*str){ count++; str++; } return count; } int main(){ int len_one = my_strlen_one("abcdef"); int len_two = my_strlen_two("abcdef"); printf("len_one = %d\n", len_one); printf("len_two = %d\n", len_two); system("pause"); return 0; }
6.递归和非递归分别实现求n的阶乘
#include <stdio.h> #include <Windows.h> int fact(int n) {//递归 if (n == 1) return 1; else return n * fact(n - 1); } int my_fact(int n) {//迭代 int j = 1; for (int i = 2; i <= n; i++) { j = j * i; } return j; } int main() { printf("%d\n", fact(3)); printf("%d\n", my_fact(3)); system("pause"); return 0; }
7.递归方式实现打印一个整数的每一位
#include <stdio.h> #include <Windows.h> void show(int n) { if (n < 10) { printf("%d\n", n); } else { printf("%d\n", n % 10); show(n / 10); } } int main() { show(234); system("pause"); return 0; }