プログラムの最適化と完成コード
これで動作するプログラムができたので、最大要素と最小要素の検索を 1 つのループにまとめることで最適化しましょう。これにより、配列を 2 回走査する必要がなくなり、効率的になります。
main.c
ファイルを開き、内容全体を次の最適化されたバージョンに置き換えます。
#include <stdio.h>
int main() {
// We'll declare an array with a maximum capacity of 50 elements
int array[50];
// Variables to store the size of the array and loop counter
int size, i;
// Variables to store the largest and smallest elements
int largest, smallest;
printf("Finding Largest and Smallest Elements in an Array\n");
printf("------------------------------------------------\n\n");
// Ask user for the size of the array
printf("Enter the size of the array (max 50): ");
scanf("%d", &size);
// Validate the input size
if (size <= 0 || size > 50) {
printf("Invalid array size. Please enter a size between 1 and 50.\n");
return 1;
}
// Get array elements from the user
printf("\nEnter %d elements of the array:\n", size);
for (i = 0; i < size; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &array[i]);
}
// Display the entered array
printf("\nThe array you entered is: [ ");
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("]\n\n");
// Initialize largest and smallest with the first element
largest = smallest = array[0];
// Find both the largest and smallest elements in a single pass
printf("Searching for largest and smallest elements...\n");
for (i = 1; i < size; i++) {
// Check for largest
if (array[i] > largest) {
largest = array[i];
printf("New largest found at position %d: %d\n", i + 1, largest);
}
// Check for smallest
if (array[i] < smallest) {
smallest = array[i];
printf("New smallest found at position %d: %d\n", i + 1, smallest);
}
}
// Display results
printf("\nResults:\n");
printf("- The largest element in the array is: %d\n", largest);
printf("- The smallest element in the array is: %d\n", smallest);
// Calculate and display the range
printf("- The range (difference between largest and smallest) is: %d\n", largest - smallest);
return 0;
}
この最適化されたバージョンは以下のようになっています。
- 1 つのループで最大要素と最小要素の両方を見つけるため、プログラムがより効率的になります。
largest
と smallest
の両方を配列の最初の要素で初期化します。
- 範囲(最大値と最小値の差)の計算を追加します。
最適化されたプログラムをコンパイルして実行しましょう。
gcc main.c -o main
./main
前と同じように配列のサイズと要素を入力します。たとえば、10、25、5、17、9 の値を入力すると、次のような出力が表示されるはずです。
Finding Largest and Smallest Elements in an Array
------------------------------------------------
Enter the size of the array (max 50): 5
Enter 5 elements of the array:
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 17
Element 5: 9
The array you entered is: [ 10 25 5 17 9 ]
Searching for largest and smallest elements...
New largest found at position 2: 25
New smallest found at position 3: 5
Results:
- The largest element in the array is: 25
- The smallest element in the array is: 5
- The range (difference between largest and smallest) is: 20
この最適化されたバージョンは以前と同じ結果を提供しますが、より効率的であり、値の範囲に関する追加情報も含まれています。
大きな配列を扱う場合、これらの効率向上により計算時間を大幅に削減でき、これはプログラミングにおいて重要な考慮事項です。