C 言語で配列の最大要素と最小要素を見つける

CCBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

配列内の最大要素と最小要素を見つけることは、プログラミングにおいて頻繁に遭遇する一般的な問題です。このスキルは、データ分析、ゲーム開発、ソートアルゴリズムなど、様々なアプリケーションにおいて不可欠です。

この実験では、整数配列内の最大要素と最小要素の両方を特定する C プログラムを書く方法を学びます。この基本的なプログラミング技術の背後にあるロジックを理解しやすくするために、プロセスを明確で管理しやすいステップに分解します。

Finding the largest and smallest elements in an array

この実験には、変数、配列、ループ、条件文などの C プログラミングの基本的な知識が必要です。このセッションの終了時までに、データセット内の極値を見つける方法を示す完全な C プログラムを作成することができるようになります。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/BasicsGroup(["Basics"]) c/BasicsGroup -.-> c/variables("Variables") c/BasicsGroup -.-> c/operators("Operators") c/ControlFlowGroup -.-> c/if_else("If...Else") c/ControlFlowGroup -.-> c/for_loop("For Loop") c/CompoundTypesGroup -.-> c/arrays("Arrays") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123271{{"C 言語で配列の最大要素と最小要素を見つける"}} c/operators -.-> lab-123271{{"C 言語で配列の最大要素と最小要素を見つける"}} c/if_else -.-> lab-123271{{"C 言語で配列の最大要素と最小要素を見つける"}} c/for_loop -.-> lab-123271{{"C 言語で配列の最大要素と最小要素を見つける"}} c/arrays -.-> lab-123271{{"C 言語で配列の最大要素と最小要素を見つける"}} c/user_input -.-> lab-123271{{"C 言語で配列の最大要素と最小要素を見つける"}} c/output -.-> lab-123271{{"C 言語で配列の最大要素と最小要素を見つける"}} end

プログラム構造のセットアップ

新しい C ファイルを作成し、プログラムの基本構造をセットアップすることから始めましょう。これには、必要なヘッダーファイル、メイン関数、および変数宣言が含まれます。

まず、プロジェクトディレクトリに移動し、main.c という名前の新しいファイルを作成します。

cd ~/project
touch main.c

次に、エディタで 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");

    return 0;
}

このコードは、プログラムの基本構造をセットアップします。各部分が何をするかを理解しましょう。

  • #include <stdio.h> は、printf()scanf() などの関数を提供する標準入出力ライブラリをインクルードします。
  • main() 関数は、プログラムのエントリーポイントです。
  • 要素数 50 の整数配列 array を宣言します。
  • size 変数は、ユーザーが入力したい要素の数を格納します。
  • i 変数は、ループカウンターとして使用されます。
  • largest および smallest 変数は、配列内で見つかった最大値と最小値を格納します。

このコードを追加した後、ファイルを保存します。これで、プログラムの基礎ができました。

ユーザー入力の取得

これでプログラムの構造が整ったので、ユーザーから入力を取得するコードを追加しましょう。配列のサイズをユーザーに尋ね、その後配列の要素を収集する必要があります。

エディタで main.c ファイルを開き、return 0; 文の前に次のコードを追加して修正します。

// 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");

このコードは以下のことを行います。

  1. ユーザーに配列のサイズの入力を促します。
  2. サイズが 1 から 50 の間であることを検証します。
  3. ユーザーに配列の各要素を 1 つずつ入力するように求めます。
  4. 入力した配列をユーザーに表示して確認します。

ここまでの内容を確認するために、プログラムをコンパイルして実行しましょう。

gcc main.c -o main
./main

配列のサイズを入力するように促すメッセージが表示されるはずです。5 などの小さな数値を入力し、その後 5 つの値を入力します。プログラムは入力した配列を表示します。

たとえば、サイズに 5 を入力し、その後 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 ]

これでユーザーから配列の要素を収集できたので、最大値と最小値を見つける作業に進むことができます。

最大要素の検索

次に、配列内の最大要素を見つけるコードを追加しましょう。戦略は以下の通りです。

  1. 最初の要素が最大であると仮定します。
  2. それ以降の各要素を現在の最大値と比較します。
  3. より大きな要素が見つかった場合、最大値を更新します。

main.c ファイルの return 0; 文の前に次のコードを追加します。

// Initialize largest with the first element of the array
largest = array[0];

// Find the largest element
printf("Finding the largest element...\n");
for (i = 1; i < size; i++) {
    if (array[i] > largest) {
        largest = array[i];
        printf("New largest found at position %d: %d\n", i + 1, largest);
    }
}

printf("\nThe largest element in the array is: %d\n\n", largest);

このコードは、配列の最初の要素で largest 変数を初期化します。その後、2 番目の要素(インデックス 1)から始めて配列を繰り返し処理し、各要素を現在の最大値と比較します。より大きな要素が見つかった場合、largest 変数を更新し、メッセージを出力します。

結果を確認するために、プログラムをコンパイルして実行しましょう。

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 ]

Finding the largest element...
New largest found at position 2: 25

The largest element in the array is: 25

これは、プログラムが配列内の最大要素を見つける方法を示しています。アルゴリズムは最初の要素を最大として始め、より大きな値が見つかるたびに更新します。

最小要素の検索

これで最大要素を見つけたので、配列内の最小要素を見つけるコードを追加しましょう。戦略は似ています。

  1. 最初の要素が最小であると仮定します。
  2. それ以降の各要素を現在の最小値と比較します。
  3. より小さな要素が見つかった場合、最小値を更新します。

main.c ファイルの return 0; 文の前に次のコードを追加します。

// Initialize smallest with the first element of the array
smallest = array[0];

// Find the smallest element
printf("Finding the smallest element...\n");
for (i = 1; i < size; i++) {
    if (array[i] < smallest) {
        smallest = array[i];
        printf("New smallest found at position %d: %d\n", i + 1, smallest);
    }
}

printf("\nThe smallest element in the array is: %d\n", smallest);

このコードは、配列の最初の要素で smallest 変数を初期化します。その後、2 番目の要素(インデックス 1)から始めて配列を繰り返し処理し、各要素を現在の最小値と比較します。より小さな要素が見つかった場合、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 ]

Finding the largest element...
New largest found at position 2: 25

The largest element in the array is: 25

Finding the smallest element...
New smallest found at position 3: 5

The smallest element in the array is: 5

これは、プログラムが配列内の最大要素と最小要素の両方を見つける方法を示しています。アルゴリズムは最初の要素から始まり、それぞれより大きいまたは小さい値が見つかるたびに更新されます。

プログラムの最適化と完成コード

これで動作するプログラムができたので、最大要素と最小要素の検索を 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. 1 つのループで最大要素と最小要素の両方を見つけるため、プログラムがより効率的になります。
  2. largestsmallest の両方を配列の最初の要素で初期化します。
  3. 範囲(最大値と最小値の差)の計算を追加します。

最適化されたプログラムをコンパイルして実行しましょう。

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

この最適化されたバージョンは以前と同じ結果を提供しますが、より効率的であり、値の範囲に関する追加情報も含まれています。

大きな配列を扱う場合、これらの効率向上により計算時間を大幅に削減でき、これはプログラミングにおいて重要な考慮事項です。

まとめ

この実験では、配列内の最大要素と最小要素の両方を見つける C プログラムを成功させました。学んだことを振り返ってみましょう。

  1. 必要な変数宣言を含む基本的なプログラム構造を設定しました。
  2. 配列のサイズと要素のユーザー入力を取得するコードを記述しました。
  3. 配列内の最大要素を見つけるアルゴリズムを実装しました。
  4. 配列内の最小要素を見つける同様のアルゴリズムを実装しました。
  5. 両方の検索を 1 つのループにまとめることでプログラムを最適化し、追加機能を追加しました。

この実験ではいくつかの基本的なプログラミング概念がカバーされています。

  • 配列と配列の走査
  • 繰り返し処理にループを使用する
  • 条件文
  • アルゴリズムの最適化
  • ユーザー入力の取得と検証

これらのスキルはすべてのプログラマーにとって不可欠であり、より複雑なデータ構造やアルゴリズムの基礎を形成します。データセット内の極値を見つける能力は、ゲームでの高得点の検索、温度測定値の分析、または金融データの処理など、多くのプログラミングシナリオで一般的な要件です。

このプログラムには、次のような機能を追加することでさらに拡張することができます。

  • すべての配列要素の平均を求める
  • 配列をソートする
  • 中央値を求める
  • 特定の値の出現回数をカウントする

これらの概念を練習し続けて、プログラミングスキルを強化しましょう。