C 語言程式查詢陣列中第二大和第二小的數


輸入陣列元素,然後使用交換技術將數字按降序排列。之後,藉助索引位置,嘗試列印陣列中第二大和第二小的元素。

陣列用於在一個名稱下儲存一組公共元素。

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

更新於: 2023-09-13

30K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告