求第n个斐波那契数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
int fib(int n)
{
if (n <= 2 ) {
return 1 ;
}
return fib(n - 1 ) + fib(n - 2 );
}
int main()
{
int n = 6 ;
printf ("%d" , fib(n));
system("pause" );
}
求n的k次方
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
int pow (int n, int k)
{
if (k == 1 )
return n;
return n * pow (n, k - 1 );
}
int main()
{
int n = 2 ;
int k = 10 ;
printf ("%d" , pow (n, k));
system("pause" );
}
输入一个非负整数,返回组成它的数字之和,例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
int DigitSum(int n)
{
if (n == 0 ) {
return 0 ;
}
return n % 10 + DigitSum(n / 10 );
}
int main()
{
int n = 1729 ;
printf ("%d" , DigitSum(n));
system("pause" );
}
递归实现字符串反转
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strlen(char * arr)
{
char * end = arr;
while (*end != '\0' ) {
end++;
}
return end - arr;
}
void reverse_string(char * arr)
{
int len = my_strlen(arr);
if (len <= 1 ) {
return ;
}
int tmp = arr[0 ];
arr[0 ] = arr[len - 1 ];
arr[len - 1 ] = '\0' ;
reverse_string(arr + 1 );
arr[len - 1 ] = tmp;
}
int main()
{
char a[] = "hello" ;
reverse_string(a);
printf ("%s" , a);
system("pause" );
}
递归和非递归分别实现strlen
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strlen(char * arr)
{
char * end = arr;
while (*end != '\0' ) {
end++;
}
return end - arr;
}
int my_strlen_r(char * arr)
{
if (*arr == '\0' )
return 0 ;
return 1 + my_strlen_r(arr + 1 );
}
int main()
{
char a[] = "hello" ;
printf ("%d" , my_strlen_r(a));
system("pause" );
}
递归求n的阶乘
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
int factorial(int n)
{
if (n == 1 )
return 1 ;
return n * factorial(n - 1 );
}
int main()
{
int n = 5 ;
printf ("%d" , factorial(n));
system("pause" );
}
递归方式实现正序打印一个整数的每一位
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
void print(int n)
{
if (n == 0 ) {
return ;
}
print(n / 10 );
printf ("%d\n" , n % 10 );
}
int main()
{
int n = 1234 ;
print(n);
system("pause" );
}