c语言数组小练习
//查找数组中最大的值: #include<stdio.h> int main01() { int a[] = { 32, 654, 31, 75, 15, 984, 19, 33, 77, 22 ,736,11}; int tmp = a[0]; int i; for(i = 1;i < sizeof(a) / sizeof(a[0]);i++) { if(a[i] > tmp) tmp = a[i]; } printf("max = %d",tmp); return 0; } //取出数组中第二大数: int main02() { int a[] = { 32, 654, 31, 75, 15, 984, 19, 33, 77, 22 ,736,11}; int max = 0; int smax = 0; int i; (a[0] > a[1])?(max = a[0],smax = a[1]):(max = a[1],smax = a[0]); for(i = 2;i < sizeof(a) / sizeof(a[0]);i++) { if(a[i] > max) { smax = max; max = a[i]; } else if(a[i] < max && a[i] > smax) { smax = a[i]; } } printf("smax = %d\n",smax); return 0; } //数组逆置 int main() { int a[] = { 32, 654, 31, 75, 15, 984, 19, 33, 77, 22 ,736,11}; //俩个元素交换的思路 //int tmp = a[0]; //a[0] = a[9]; //a[9] = tmp; int min = 0; int max = 0; int i; max = sizeof(a) / sizeof(a[0]) - 1; while(min < max) { int tmp = a[min]; a[min] = a[max]; a[max] = tmp; min++; max--; } for(i = 0;i < sizeof(a) / sizeof(a[0]);i++) { printf("a[%d]=%d\n",i,a[i]); } return 0; } //冒泡排序: int main() { int a[] = {32, 654, 31, 75, 15, 984, 19, 33, 77, 22 ,736,11}; int i,j; int max = sizeof(a) / sizeof(a[0]); for(i = 0;i < max;i++) { for(j = 1;j < max - i;j++) { if(a[j-1] > a[j])//前面的元素大于后面的元素 { int tmp = a[j-1]; a[j-1] = a[j]; a[j] = tmp; } } } for(i = 0;i < max;i++) { printf("a[%d] = %d\n",i,a[i]); } return 0; }