輸入陣列元素,然後使用交換技術按降序排列數字。隨後,在索引位置的幫助下,嘗試列印數組中第二大和第二小的元素。
陣列用來保存同一個名稱下的一組公共元素。
陣列用來保存同一個名稱下的一組公共元素。 p>
C 語言中的數組操作如下-
#步驟1 - 聲明並讀取元素數。 strong>
步驟 2 - 在執行階段宣告並讀取陣列大小。
步驟 3 - 輸入陣列元素。
步驟 4 - 依降序排列數字。
步驟 5 - 然後,使用索引找到第二大和第二小的數字。
步驟 6 - 列印第二大和第二小的數字。
程序查找數組中第二大和第二小的數字 -
#include<stdio.h> void main(){ int i,j,a,n,counter,ave,number[30]; printf ("Enter the value of N</p><p>"); scanf ("%d", &n); printf ("Enter the numbers </p><p>"); 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</p><p>"); for (i=0; i<n; ++i) printf ("%10d</p><p>",number[i]); printf ("The 2nd largest number is = %d</p><p>", number[1]); printf ("The 2nd smallest number is = %d</p><p>", 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</p><p>"); else printf("The average of 2nd largest & 2nd smallest in array is %d in numbers</p><p>", 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
以上是C程式用於在陣列中找到第二大和第二小的數字的詳細內容。更多資訊請關注PHP中文網其他相關文章!