作业1:使用递归实现n!
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int fun(int n)
{if(0==n){return 1;}else{return n*fun(n-1);}
}
int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int sum=fun(n);printf("n!=%d\n",sum);return 0;
}
效果图:
作业2:使用递归实现0-n的和
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int fun(int n)
{if(0==n){return 0;}else{return n+fun(n-1);}
}
int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int sum=fun(n);printf("sum=%d\n",sum);return 0;
}
效果图:
作业3:使用递归实现斐波那契
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int fun(int n)
{if(n<=2){return 1;}else{return fun(n-1)+fun(n-2);}
}
int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);for(int i=1;i<=n;i++){printf("%-4d",fun(i));}puts("");return 0;
}
效果图:
作业4:使用递归实现二进制转换
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void fun(int n)
{if(n==0){return;}else{fun(n/2);printf("%d",n%2);}
}
int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);fun(n);puts("");return 0;
}
效果图:
作业5:使用递归实现各个位数字之和
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int fun(int n)
{if(0==n){return 0;}else{return n%10+fun(n/10);}
}
int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int sum=fun(n);printf("sum=%d\n",sum);return 0;
}
效果图:
作业6:使用递归实现各个位数字的乘积
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int fun(int n)
{if(0==n){return 1;}else{return n%10*fun(n/10);}
}
int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int mul=0;if(0==n){mul=0;}else{mul=fun(n);}printf("mul=%d\n",mul);return 0;
}
效果图:
作业7:使用递归实现单词逆置
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void fun(char *p,int low,int high)
{if(low>=high){return;}else{char t=*(p+low);*(p+low)=*(p+high);*(p+high)=t;fun(p,low+1,high-1);}
}
int main(int argc, const char *argv[])
{char str[20]="";printf("please enter str:");gets(str);int len=strlen(str);fun(str,0,len-1);puts(str);return 0;
}
效果图: