Beginner C/C++ Exercises

Character Frequency

A frequency table maps each possible character to a counter.

What is Character Frequency?

A frequency table maps each possible character to a counter.

Count occurrences of each lowercase letter.

Important points

  • Compile with warnings enabled and fix every warning.
  • Know the lifetime and type of every value.
  • Validate input and keep array bounds explicit.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>
int main(void) {
    const char *text = "banana"; int counts[26] = {0};
    // Convert each lowercase letter to an array index.
    for (; *text; ++text) ++counts[*text - 'a'];
    for (int i = 0; i < 26; ++i) if (counts[i]) printf("%c=%d\n", 'a' + i, counts[i]);
}
Expected output
a=3
b=1
n=2
C++
Run code →
main.cpp
#include <array>
#include <iostream>
#include <string>
int main() {
    std::string text = "banana"; std::array<int, 26> counts{};
    // Convert each lowercase letter to an array index.
    for (char character : text) ++counts[character - 'a'];
    for (size_t i = 0; i < counts.size(); ++i) if (counts[i]) std::cout << char('a' + i) << '=' << counts[i] << '\n';
}
Expected output
a=3
b=1
n=2

C and C++ comparison

Use the character offset from a as the array index and print only nonzero counts.

C

C exposes small procedural APIs and makes representation details explicit.

C++

C++ retains the low-level model while adding safer library types and abstractions.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Add invalid and boundary-value inputs.
  • Compile with -Wall -Wextra -Wpedantic.
  • Move reusable declarations into a header and implementation file.