🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Strings · Lecture 36
C Character Frequency Counter
Count how often every character appears in a string using a lookup table, the way real embedded C code does it. Part of our free C programming course for embedded systems.
Counting characters sounds like a classroom exercise, but the idea behind it shows up everywhere in firmware: histograms of received UART bytes, checksum tables, protocol analysers and log filters. In this lecture of our free C programming course you will build a character frequency counter in C the efficient way, with one pass over the string and a small table, and you will learn why the nested-loop approach many old textbooks use is slow and fragile. If you are following this free C tutorial to prepare for embedded C programming work, this is a pattern worth having in your toolbox.
What You Will Learn
- What a frequency table is and why it beats nested loops
- How a character becomes an array index in C
- Why
unsigned charmatters when you index with characters - How to read a line safely with
fgetsinstead ofscanf("%s") - How to build a letter histogram with case folding
- How the same trick counts bytes from a UART or sensor stream
Prerequisites
You should be comfortable with one-dimensional arrays, for loops, and the basics of C strings (the NUL terminator and strlen) from the earlier lectures of this free embedded C course. A C compiler such as GCC on Linux, or any ARM GNU toolchain for your board, is enough to try every example.
The Problem: Character Frequency in C
Given a string, print every distinct character together with the number of times it occurs. For the text embedded c the answer is: d three times, e three times, and each of the other characters once, including the space.
Why the Nested-Loop Way Is a Poor Habit
A common beginner solution takes each character, scans the rest of the string to count matches, and then blanks out the matched characters so they are not counted again. It works on small inputs, but it has three problems you should recognise:
- It destroys the input. Overwriting matched characters with spaces means the original string is gone afterwards.
- It is O(n²). A 1000-byte buffer needs about a million comparisons.
- It mixes real spaces with “already counted” markers, so genuine spaces in the data are silently skipped.
Another trap lives next to it: reading into a tiny fixed array with scanf("%s", str) has no length limit, so any input longer than the array overruns the buffer. We will avoid both problems.
The Frequency Table Idea
A char in C is just a small integer. That means a character can be used directly as an array index. If you create an array with one counter per possible character value, then “count this character” becomes a single increment: freq[ch]++. One pass over the string, no nested loops, no modification of the input.
How freq[ch]++ works for the text “dad”
With 8-bit characters there are 256 possible values (0 to 255), so the table is UCHAR_MAX + 1 counters. On a microcontroller, 256 counters of 1 or 2 bytes each is a perfectly reasonable cost for a debugging histogram.
Warning: use unsigned char for the index. Plain char may be signed on your platform. A byte such as 0xE9 would then become a negative number, and freq[-23] writes outside your array. Cast to unsigned char before using a character as an index.
Program 1: Count Every Character
This program reads one line, counts every byte, and prints only the characters that actually appeared. It uses fgets, which takes the buffer size and therefore cannot overflow it, and strcspn to strip the newline.
#include <stdio.h>
#include <string.h>
#include <limits.h>
int main(void)
{
char line[64];
unsigned int freq[UCHAR_MAX + 1] = {0};
printf("Enter text: ");
if (fgets(line, sizeof line, stdin) == NULL)
return 1;
line[strcspn(line, "\n")] = '\0';
for (const unsigned char *p = (const unsigned char *)line; *p != '\0'; p++)
freq[*p]++;
for (int c = 0; c <= UCHAR_MAX; c++) {
if (freq[c] == 0)
continue;
if (c == ' ')
printf("[space] : %u\n", freq[c]);
else
printf("'%c' : %u\n", c, freq[c]);
}
printf("original string still intact: \"%s\"\n", line);
return 0;
}
Build and Run
$ gcc -std=c11 -Wall -Wextra -o freq freq.c
$ echo "embedded c" | ./freq
Expected Output
Enter text: [space] : 1
'b' : 1
'c' : 1
'd' : 3
'e' : 3
'm' : 1
original string still intact: "embedded c"
Notice that the characters come out in ASCII order, not in the order they appeared. That is a free side effect of walking the table from index 0 upwards, and it is often exactly what you want.
How the Code Works
| Line | What it does |
|---|---|
unsigned int freq[UCHAR_MAX + 1] = {0}; | One counter per possible byte value, all starting at zero |
fgets(line, sizeof line, stdin) | Reads at most 63 characters, always NUL-terminates |
line[strcspn(line, "\n")] = '\0'; | Finds the newline (or the end) and cuts the string there |
freq[*p]++ | Uses the character value as the index and bumps its counter |
if (freq[c] == 0) continue; | Skips characters that never appeared |
Program 2: Letter Histogram with Case Folding
Often you only care about letters and want A and a counted together. A table of 26 counters is enough, and the index comes from simple arithmetic: tolower(ch) - 'a'. This works for English letters because their codes are consecutive in ASCII.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
const char *text = "Embedded C makes Every Byte count";
unsigned int letters[26] = {0};
for (const char *p = text; *p != '\0'; p++) {
if (isalpha((unsigned char)*p))
letters[tolower((unsigned char)*p) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (letters[i] == 0)
continue;
printf("%c ", 'a' + i);
for (unsigned int k = 0; k < letters[i]; k++)
putchar('#');
printf(" (%u)\n", letters[i]);
}
return 0;
}
Expected Output
a # (1)
b ## (2)
c ## (2)
d ### (3)
e ####### (7)
k # (1)
m ## (2)
n # (1)
o # (1)
r # (1)
s # (1)
t ## (2)
u # (1)
v # (1)
y ## (2)
Each letter prints a bar of # marks followed by its count, which gives a quick text histogram. Because only letters pass the isalpha test, the index is always between 0 and 25 and the array can never be overrun.
Tip
Always pass isalpha, tolower and friends an unsigned char value. Passing a negative char to the <ctype.h> functions is undefined behaviour.
Real-World Use: Byte Statistics in Embedded C Programming
The same table works on any byte buffer, not just text. Imagine a UART receive buffer of 512 bytes from a sensor. A 256-entry histogram tells you at a glance whether the line is idle (mostly 0xFF), whether the baud rate is wrong (random garbage), or whether a protocol uses a delimiter byte at the expected rate. The loop is identical: hist[buf[i]]++.
| Use case | Table size | Index source |
|---|---|---|
| Text character count | 256 | the character itself |
| Letters only, case-insensitive | 26 | tolower(ch) - 'a' |
| Digit count | 10 | ch - '0' |
| UART byte histogram | 256 | the received byte |
Performance Considerations
- The table method is O(n) for a string of n characters plus a fixed 256-step print loop. The nested-loop method is O(n²).
- Use a smaller counter type (
uint8_toruint16_t) if RAM is tight, but make sure the counter cannot overflow for your maximum input size. - If the data is tiny and sparse, a table of 256 counters might waste RAM. In that case sorting a copy of the data and counting runs is another option.
Common Mistakes
- Forgetting to initialise the table. A local array is full of garbage until you write
= {0}. - Indexing with a signed char. Cast to
unsigned charfirst. - Using a table of 128 entries and then feeding it bytes above 127.
- Using scanf(“%s”) into a small array. It stops at whitespace and has no length limit. Use
fgets. - Forgetting the newline.
fgetskeeps it, so it would be counted as a character unless you remove it.
Best Practices
- Size tables with
UCHAR_MAX + 1rather than a magic 256. - Keep the input read-only (
constpointers) so counting cannot damage it. - Validate before you index: for letter tables, check
isalphafirst. - Print with a clear label for non-printable bytes such as space, tab and newline.
Suggested Images
| Image idea | Suggested ALT text |
|---|---|
| Frequency table filled in for a short word | character frequency counter in C using a lookup table, free C programming course |
| Terminal screenshot of the program output | C program output counting characters, free C tutorial for embedded C programming |
| UART buffer feeding a 256-entry histogram | byte histogram in embedded C programming, free embedded C course |
Summary and Key Takeaways
- A frequency table turns “count each character” into one increment per character.
- The character value is the array index, so cast to
unsigned charfirst. - The method is O(n), keeps the input intact, and works for any byte data.
- Read lines with
fgets, and strip the newline withstrcspn. - The same idea builds histograms for letters, digits and raw UART bytes.
Conclusion
You now know a cleaner way to count characters than the nested-loop pattern, and the technique transfers directly to embedded C programming, where lookup tables are one of the most useful tools you have. In the next lecture of this free embedded C course we will use the same lookup-table thinking to turn a number into English words.
Frequently Asked Questions
Why not use a nested loop to count characters?
It is O(n²), it usually modifies the input, and it confuses real spaces with “already counted” markers. A table is faster and safer.
Why is the table 256 entries long?
An 8-bit character has 256 possible values, so one counter per value covers every byte.
Do I need unsigned char for the index?
Yes. Plain char can be negative on some platforms, which would index before the start of the array.
Why use fgets instead of scanf with %s?
fgets takes the buffer size and cannot overflow it. scanf with %s has no limit and stops at the first space.
Does this work for Unicode text?
It counts bytes, not characters. UTF-8 characters can use several bytes, so you would need a different approach for true Unicode counting.
Can I use this on a microcontroller with little RAM?
Yes. Use uint8_t or uint16_t counters, or reduce the table to just the characters you care about.
Keep Learning with the Free C Programming Course
Join thousands of students learning embedded C programming for free. Continue with the next lecture or revisit the course index.

2 Comments