C7
1、 编写一个函数 reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。
#include<stdio.h>
#include<stdlib.h>
int strlen_2(char *str){
if (*str){
return 1 + strlen_2(str + 1);
}
return 0;
}
void reverse_string(char *str){
int end = strlen_2(str) - 1;
char tmp = str[0];
if (str[0]){
str[0] = str[end];
str[end] = '\0';
reverse_string(str + 1);
str[end] = tmp;
}
}
int main(){
char arr[] = "you are cute";
reverse_string(arr);
puts(arr);
system("pause");
return 0;
}
2.递归和非递归分别实现strlen
#include<stdio.h>
#include<stdlib.h>
int strlen_1(char *str){
int i;
for (i = 0; str[i]; i++);
return i;
}//非递归方式
int strlen_2(char *str){
if (*str){
return 1 + strlen_2(str + 1);
}
return 0;
}
int main()
{
printf("%d\n", strlen_1("you are cute"));
printf("%d\n", strlen_2("you are cute"));
system("pause");
return 0;
}
3.递归和非递归分别实现求n的阶乘
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int factorial_1(int n) {
if (n == 1) {
return 1;
}
return n * factorial_1(n - 1);
}
int factorial_2(int n) {
int num = 1;
int i=1;
for (i = 1; i <= n; ++i) {
num *= i;
}
return num;
}
void main() {
int n;
printf("请输入n的值\n");
scanf("%d", &n);
printf("递归求得阶乘为:%d\n", factorial_1(n));
printf("非递归求得阶乘为:%d\n", factorial_2(n));
system("pause");
}
4.递归方式实现打印一个整数的每一位.
#include<stdio.h>
#include<stdlib.h>
int PrintNum(int n){
if (n){
PrintNum(n / 10);
printf("%d", n % 10);
}
}
int main()
{
printf("%d\n", PrintNum(1729));
system("pause");
return 0;
}