C言語実践問題集:配列・文字列・ポインタを活用したプログラミング課題

本稿では、C言語の基礎から応用までを網羅する一連の実践演習問題を提供します。各問題は「穴埋め」「誤り訂正」「関数実装」の3形式で構成され、配列操作、文字列処理、ポインタの使い方、およびアルゴリズム的思考力を段階的に鍛える設計となっています。

問題セットA:数字の出現頻度と配列操作

以下の関数は、整数値の各桁に含まれる0〜9の数字の出現回数をカウントし、10要素の配列に格納します。

#include <stdio.h>
void countDigits(int value, int counts[10]) {
    for (int idx = 0; idx < 10; ++idx) {
        counts[idx] = 0;
    }
    int temp = value;
    while (temp > 0) {
        int digit = temp % 10;
        counts[digit]++;
        temp /= 10;
    }
}

int main() {
    int input, results[10];
    printf("整数を入力してください: ");
    scanf("%d", &input);
    countDigits(input, results);
    for (int i = 0; i < 10; ++i) {
        printf("%d,", results[i]);
    }
    printf("\n");
    return 0;
}

問題セットB:文字列解析と大文字小文字の統一処理

次の関数は、英字のみからなる文字列を受け取り、各アルファベットの出現頻度(大文字・小文字を区別しない)を計算し、最も多く登場した文字を出力します。

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void findMostFrequentChar(const char str[]) {
    int freq[26] = {0};
    int len = strlen(str);

    for (int i = 0; i < len; ++i) {
        if (isalpha(str[i])) {
            char lower = tolower(str[i]);
            freq[lower - 'a']++;
        }
    }

    int maxIndex = 0;
    for (int j = 1; j < 26; ++j) {
        if (freq[j] > freq[maxIndex]) {
            maxIndex = j;
        }
    }

    printf("最頻出文字: %c\n", 'a' + maxIndex);
}

問題セットC:文字列から数値への安全変換

文字列を符号なし長整数に変換する関数を実装します。空文字列や非数字文字の検証は省略しますが、基本的な桁ごとの乗算による変換ロジックを示します。

long stringToLong(const char* digits) {
    long result = 0;
    int pos = 0;
    while (digits[pos] != '\0') {
        if (digits[pos] >= '0' && digits[pos] <= '9') {
            result = result * 10 + (digits[pos] - '0');
        }
        ++pos;
    }
    return result;
}

問題セットD:単方向連結リストの構築と走査

3つのノードを順に連結し、データフィールドの内容を順に出力するコード例です。ポインタの代入と構造体間のリンクを明確に表現しています。

#include <stdio.h>

typedef struct Node {
    char value;
    struct Node* next;
} Node;

void buildAndPrint(Node* first, Node* second, Node* third) {
    first->next = second;
    second->next = third;
    third->next = NULL;

    Node* current = first;
    while (current != NULL) {
        printf(" %c", current->value);
        current = current->next;
    }
    printf("\n");
}

問題セットE:部分配列探索とインデックス検索

配列内で指定された値が最初に現れる位置(0ベースのインデックス)を返す関数です。該当要素がない場合は−1を返します。

int locateValue(const int array[], int size, int target) {
    for (int i = 0; i < size; ++i) {
        if (array[i] == target) {
            return i;
        }
    }
    return -1;
}

タグ: c-language arrays strings pointers Algorithm

10月19日 14:22 投稿