[C言語]配列から数字の個数を数える!文字列配列のカウントについても

C言語
広告

C言語において配列から同じ数字が何個含まれているか出現回数を数える方法は実務で頻繁に利用されます。

この記事ではその手法について初心者向けに解説します。

同じ数字の個数を効率的に数える方法や同じ文字のカウントの取り方についても学びましょう。

SPONSORLYNC

数値配列から同じ数字の個数を数える

同じ数字の個数を数えるには、配列を順番に調査しながら、

対象となる数字と一致するかどうかを確認します。

以下はそのためのサンプルコードです。

#include <stdio.h>

int countOccurrences(int array[], int size, int target) {
    int count = 0;

    for (int i = 0; i < size; i++) {
        if (array[i] == target) {
            count++;
        }
    }

    return count;
}

int main() {
    int numbers[] = {1, 2, 3, 4, 2, 5, 2, 6};
    int targetNumber = 2;

    int occurrences = countOccurrences(numbers, sizeof(numbers) / sizeof(numbers[0]), targetNumber);

    // 結果の表示
    printf("配列中に %d は %d 個含まれています。\n", targetNumber, occurrences);

    return 0;
}

この例では、countOccurrences関数を使って、指定した数字の個数を数えています。

関数の引数には、対象となる配列、配列のサイズ、および対象となる数字が渡されます。

広告

文字列配列から同じ文字のカウントを取る

char配列から同じ文字のカウントを行う方法は文字列を一つずつ調査しながら、

各文字が出現した回数を数えることです。以下はそのためのサンプルコードです。

#include <stdio.h>
void countCharacters(const char *str) {
    int count[256] = {0};  // ASCII文字全ての出現回数を格納する配列

    // 文字列を調査して出現回数をカウント
    while (*str != '
#include <stdio.h>
void countCharacters(const char *str) {
    int count[256] = {0};  // ASCII文字全ての出現回数を格納する配列

    // 文字列を調査して出現回数をカウント
    while (*str != '\0') {
        count[(unsigned char)*str]++;
        str++;
    }

    // 結果の表示
    for (int i = 0; i < 256; i++) { if (count[i] > 0) {
            printf("'%c' の出現回数: %d\n", i, count[i]);
        }
    }
}

int main() {
    char myCharArray[] = {'a', 'b', 'c', 'a', 'b', 'c', 'a', 'a', '\0'};

    // 同じ文字のカウントを行う
    countCharacters(myCharArray);

    return 0;
}
') { count[(unsigned char)*str]++; str++; } // 結果の表示 for (int i = 0; i < 256; i++) { if (count[i] > 0) { printf("'%c' の出現回数: %d\n", i, count[i]); } } } int main() { char myCharArray[] = {'a', 'b', 'c', 'a', 'b', 'c', 'a', 'a', '
#include <stdio.h>
void countCharacters(const char *str) {
    int count[256] = {0};  // ASCII文字全ての出現回数を格納する配列

    // 文字列を調査して出現回数をカウント
    while (*str != '\0') {
        count[(unsigned char)*str]++;
        str++;
    }

    // 結果の表示
    for (int i = 0; i < 256; i++) { if (count[i] > 0) {
            printf("'%c' の出現回数: %d\n", i, count[i]);
        }
    }
}

int main() {
    char myCharArray[] = {'a', 'b', 'c', 'a', 'b', 'c', 'a', 'a', '\0'};

    // 同じ文字のカウントを行う
    countCharacters(myCharArray);

    return 0;
}
'}; // 同じ文字のカウントを行う countCharacters(myCharArray); return 0; }

この例では、countCharacters 関数を使って char 配列から同じ文字のカウントを行っています。

count 配列には、各文字の出現回数が格納され、最終的にそれを表示しています。

広告

まとめ

まとめ

C言語において、配列から同じ数字の個数を数える方法は、

単純なループと条件分岐を使用して実現できます。

これを活かして、配列処理の基礎を身につけましょう。

C言語
広告
塩竈Code
タイトルとURLをコピーしました