1. 升序数组插入元素
#include"stdio.h"
#define N 20
void insert(int arr[], int* len, int num){
int i=0,j;
while(arr[i] < num)
i++;
for(j=*len;j>i;j--)
arr[j] = arr[j-1];
arr[i] = num;
*len++;
}
void show(int arr[], int* len){
int i;
for(i=0;i<*len;i++)
printf("%4d",arr[i]);
printf("\n");
}
int main(){
int num[N],n,len=0;
int i=0;
scanf("%d",&n);
while(n != -1){
num[i] = n;
len++;
scanf("%d",&n);
i++;
}
printf("插入元素: ");
scanf("%d",&n);
insert(num,&len,n);
show(num,&len);
}
2. n×n阶矩阵,计算两条对角线上的各元素之和
#include"stdio.h"
#define N 10
void input(int s[][N], int n){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++)
scanf("%d",&s[i][j]);
}
}
int sum(int s[][N], int n){
int i,j,sum=0;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(i==j||i+j==n-1)
sum += s[i][j];
}
}
return sum;
}
int main(){
int num[N][N];
int n;
printf("输入矩阵维度: ");
scanf("%d",&n);
input(num,n);
printf("对角线元素之和: %d\n",sum(num,n));
return 0;
}
3. 打印杨辉三角
#include"stdio.h"
#define N 20
int main(){
int str[N][N];
int n,i,j;
printf("行数: ");
scanf("%d",&n);
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
str[i][j] = 1;
}
}
for(i=1;i<=n;i++){
for(j=2;j<=i-1;j++){
str[i][j] = str[i-1][j] + str[i-1][j-1];
}
}
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
printf("%4d",str[i][j]);
}
printf("\n");
}
return 0;
}
4. 汉诺塔
#include"stdio.h"
void move(char a, char b){
printf("%c-------->%c\n",a,b);
}
void hanio(char a, char b, char c, int n){
if(n==1)
move(a,b);
else{
hanio(a,c,b,n-1);
move(a,b);
hanio(c,b,a,n-1);
}
}
int main(){
int n;
printf("输入汉诺塔层数: ");
scanf("%d",&n);
hanio('A','B','C',n);
return 0;
}