C 语言程序查找数组中第二大和第二小的数
输入数组元素,然后使用交换技术将数字按降序排列。之后,借助索引位置,尝试打印数组中第二大和第二小的元素。
数组用于在一个名称下保存一组公共元素。
- 插入
- 删除
- 搜索
算法
下面是查找数组中第二大和第二小数字的算法:
步骤 1 - 声明并读取元素数量。
步骤 2 - 在运行时声明并读取数组大小。
步骤 3 - 输入数组元素。
步骤 4 - 将数字按降序排列。
步骤 5 - 然后,使用索引查找第二大和第二小的数字。
步骤 6 - 打印第二大和第二小的数字。
程序
下面是用于查找数组中第二大和第二小数字的 C 程序:
#include<stdio.h> void main(){ int i,j,a,n,counter,ave,number[30]; printf ("Enter the value of N
"); scanf ("%d", &n); printf ("Enter the numbers
"); for (i=0; i<n; ++i) scanf ("%d",&number[i]); for (i=0; i<n; ++i){ for (j=i+1; j<n; ++j){ if (number[i] < number[j]){ a = number[i]; number[i] = number[j]; number[j] = a; } } } printf ("The numbers arranged in descending order are given below
"); for (i=0; i<n; ++i) printf ("%10d
",number[i]); printf ("The 2nd largest number is = %d
", number[1]); printf ("The 2nd smallest number is = %d
", number[n-2]); ave = (number[1] +number[n-2])/2; counter = 0; for (i=0; i<n; ++i){ if (ave==number[i]) ++counter; } if (counter==0) printf("The average of 2nd largest & 2nd smallest is not in the array
"); else printf("The average of 2nd largest & 2nd smallest in array is %d in numbers
", counter); }
输出
执行上述程序时,会产生以下结果:
Enter the value of N 5 Enter the numbers 10 12 17 45 80 The numbers arranged in descending order are given below 80 45 17 12 10 The 2nd largest number is = 45 The 2nd smallest number is = 12 The average of 2nd largest & 2nd smallest is not in the array
广告