- x^n(递归算法)
#include<stdio.h>
int pow(int x, int n)
{
if (n == 0)
{
return 1;
}
else
{
return x * pow(x, n - 1);
}
}
int main()
{
int x, n, sum;
printf("请输入x,n:\n");
scanf("%d %d", &x, &n);
sum = pow(x, n);
printf("求得%d的%d次幂为%d\n", x, n, sum);
return 0;
}
- n元数组排序(递归算法)(由小到大的顺序)
#include <stdio.h>
#include <stdlib.h>
void insert_sort_rec(int a[], int n) {
if (n <= 1) {
return;
}
insert_sort_rec(a, n - 1);
int key = a[n - 1];
int j = n - 2;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
int main()
{
int n;
printf("输入n元数组n的值:\n");
scanf("%d",&n);
int *a = (int*)malloc(n * sizeof(int)); // 动态分配内存
printf("输入数组的值:\n");
for(int i = 0;i < n;i++){
scanf("%d", &a[i]);
}
insert_sort_rec(a,n);
for (int j = 0;j < n;j++ ) {
printf("%d\t", a[j]);
}
free(a); // 释放内存
return 0;
}