1、利用递归计算0-n的和
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int rec(int n)
{if(n==0)return 0;elsereturn n+rec(n-1);
}
int main(int argc, const char *argv[])
{int n=0;printf("please enter n:");scanf("%d",&n);int sum=rec(n);printf("sum=%d\n",sum);return 0;
}
2、利用递归计算n!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int rec(int n)
{if(n==0)return 1;elsereturn n*rec(n-1);
}
int main(int argc, const char *argv[])
{int n=0;printf("please enter n:");scanf("%d",&n); int s=rec(n);printf("s=%d\n",s);return 0;
}
3、利用递归计算各个位数字之和
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int rec(int n)
{if(n==0)return 0;elsereturn n%10+rec(n/10);
}
int main(int argc, const char *argv[])
{int n=0;printf("please enter n:");scanf("%d",&n); int s=rec(n);printf("s=%d\n",s);return 0;
}