试题1:将一整数逆序后放入一组数组,要求递归实现。
代码实现:
#include "stdio.h" void convert(int *result, int n); int main(int argc,char* argv[]) { int n = 123456789,result[20] = {0}; convert(result, n); printf("%d:n", n); for (int i = 0; i < 9;i++) { printf("%d", result[i]); } printf("n"); system("pause"); return 0; } void convert(int *result, int n) { if (n>=10) { convert(result + 1, n / 10); } *result = n % 10; }
实现结果:
试题2:求高于平均分的学生学号及成绩,学号和成绩人工输入。
代码实现:
#include "stdio.h" double find(int total, int n); int main() { find(0, 0); system("pause"); return 0; } double find(int total, int n) { int number, score, average; //学号、分数、平均分 scanf("%d", &number); if (number!=0) { scanf("%d", &score); average = find(total + score, +n + 1); if (score>=average) { printf("%d:%dn", number, score); } return average; } else { printf("Average=%dn", total / n); return total / n; } }
试题3:递归实现回文判断,例如a-b-c-d-e-d-c-b-a就是回文,这是判断一个面试者对递归理解的简单程序。
代码实现:
#include "stdio.h" int find(char* str, int n); int main(int argc,char* argv[]) { char *str = "abcdedcba"; printf("%s:%sn", str, find(str, strlen(str))? "Yes" : "No"); system("pause"); return 0; } int find(char* str, int n) { if (n<=1) { return 1; } else if (str[0]==str[n-1]) { return find(str + 1, n - 2); } else { return 0; } }
试题4:从M个不同字符串任取N个字符的所有组合,考察了组合问题。
代码实现:
#include "stdio.h" void find(char *source, char *result, int n); int main(int argc, char *argv) { int const n = 3; char *source = "ABCDE", result[4] = { 0 }; if (n>0&&strlen(source)>0&&n<=strlen(source)) { find(source, result, 3); } system("pause"); return 0; } void find(char *source, char *result, int n) { if (n==1) { while (*source) { printf("%s%cn", result, *source++); } } else { int i, j; for (i = 0; source[i] != 0; i++); for (j = 0; result[j] != 0; j++); for (; i >= n;i--) { result[j] = *source++; result[j + 1] = '