C PROGRAMMING PROGRAM • STRINGS

Count the Frequency of Every Character

Learn how to count the frequency of every character using a clear C program.

IntermediateStringsASCII tableFrequency array

PROBLEM UNDERSTANDING

Input and expected output

Sample input
hello
Sample output
e : 1
h : 1
l : 2
o : 1

COMPLETE C PROGRAM

Complete C implementation

frequency-of-every-character-string.c
Open in compiler
#include <stdio.h>

int main(void)
{
    char text[300];
    int frequency[256] = {0};

    fgets(text, sizeof text, stdin);
    for (int index = 0; text[index] != '\0' && text[index] != '\n'; index++)
        frequency[(unsigned char) text[index]]++;
    for (int value = 0; value < 256; value++)
        if (frequency[value] > 0) printf("%c : %d\n", value, frequency[value]);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

e : 1
h : 1
l : 2
o : 1
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Use each unsigned character code as an index into a 256-entry frequency array.
  3. Display the computed result.

Use each unsigned character code as an index into a 256-entry frequency array.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.