1.递归和非递归分别实现求第n个斐波那契数。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>int fib(int n)
{if (n <= 2)return 1;elsereturn fib(n - 1) + fib(n - 2);
}int main()
{int n = 0;int ret = 0;scanf("%d", &n);ret = fib(n);printf("%d\n", ret);system("pause");return 0;
}
2.编写一个函数实现n^k,使用递归实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>int fun(int n, int k)
{if (k == 0)return 1;else if (k == 1)return n;return n * fun(n, k - 1);
}int main()
{int n = 0;int k = 0;scanf("%d %d", &n, &k);int c = fun(n, k);printf("%d\n", c);system("pause");return 0;
}
3. 写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,
例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>int DigitSum(int n)
{if (n < 0)return -1;else if(n >= 0 && n <= 9)return n;return (n % 10) + DigitSum(n / 10);
}int main()
{int num = 0;scanf("%d", &num);int ret = DigitSum(num);printf("%d\n", ret);system("pause");return 0;
}
4. 编写一个函数 reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。
#include<stdio.h>
#include<stdlib.h>char reverse_string(char *string)
{if (*string == '\0')printf("%c", *string);else{reverse_string(++string);printf("%c", *(--string));}
}int main()
{char *a = "abcde";reverse_string(a);printf("\n");system("pause");return 0;
}
5.递归和非递归分别实现strlen
递归
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>int my_strl(char *p)
{assert(p != NULL);if (*p == '\0')return 0;elsereturn 1 + my_strl(p + 1);
}int main()
{char *a = "abcdefg";int ret = my_strl(a);printf("%d\n", ret);system("pause");return 0;
}
非递归
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>int my_strl(char *p)
{assert(p != NULL);int num = 0;while (*p){num++;p++;}return num;
}int main()
{char *a = "abcdefg";int ret = my_strl(a);printf("%d\n", ret);system("pause");return 0;
}
6.递归和非递归分别实现求n的阶乘
递归
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>int fun(int n)
{if (n == 1)return 1;elsereturn n * fun(n - 1);
}int main()
{int num = 0;scanf("%d", &num);int ret = 0;ret = fun(num);printf("%d\n", ret);system("pause");return 0;
}非递归
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>int fun(int n)
{int sum = 1;for (int i = 1; i <= n; ++i){sum = sum * i;}return sum;
}
int main()
{int num = 0;scanf("%d", &num);int ret = 0;ret = fun(num);printf("%d\n", ret);system("pause");return 0;
}
7.递归方式实现打印一个整数的每一位
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>void Prit(int num)
{if (num < 10)printf("%d\n", num);else{Prit(num / 10);printf("%d\n", num % 10);}
}int main()
{int num = 0;scanf("%d", &num);Prit(num);system("pause");return 0;
}