首页 > 文章列表 > C程序用于在数组中找到第二大和第二小的数字

C程序用于在数组中找到第二大和第二小的数字

数组 第二大 第二小
326 2023-08-30

输入数组元素,然后使用交换技术按降序排列数字。随后,在索引位置的帮助下,尝试打印数组中第二大和第二小的元素。

数组用于保存同一个名称下的一组公共元素。

数组用于保存同一个名称下的一组公共元素。 p>

C 语言中的数组操作如下 -

  • 插入
  • 删除
  • 搜索

算法

下面给出的是一种查找数组中第二大和第二小的数字的算法 -

步骤 1 - 声明并读取元素数量。

步骤 2 - 在运行时声明并读取数组大小。

步骤 3< /strong> - 输入数组元素。

步骤 4 - 按降序排列数字。

步骤 5 - 然后,使用索引找到第二大和第二小的数字。

步骤 6 - 打印第二大和第二小的数字。

程序< /h2>

下面给出的是 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