C PROGRAMMING PROGRAM • LOOPS & NUMBER PROBLEMS

Count the Frequency of Every Digit

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

IntermediateFrequency arrayDigitsCounting

PROBLEM UNDERSTANDING

Input and expected output

Sample input
1202205
Sample output
0 occurs 2 time(s)
1 occurs 1 time(s)
2 occurs 3 time(s)
5 occurs 1 time(s)

COMPLETE C PROGRAM

Complete C implementation

digit-frequency-number.c
Open in compiler
#include <stdio.h>

int main(void)
{
    long long number, value;
    int frequency[10] = {0};

    printf("Enter an integer: ");
    scanf("%lld", &number);
    value = number < 0 ? -number : number;
    do {
        frequency[value % 10]++;
        value /= 10;
    } while (value > 0);
    for (int digit = 0; digit <= 9; digit++) {
        if (frequency[digit] > 0)
            printf("%d occurs %d time(s)\n", digit, frequency[digit]);
    }
    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

0 occurs 2 time(s)
1 occurs 1 time(s)
2 occurs 3 time(s)
5 occurs 1 time(s)
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Use the extracted digit as an index into a fixed ten-element frequency array.
  3. Display the computed result.

Use the extracted digit as an index into a fixed ten-element frequency array.

EFFICIENCY

Time and space complexity

Time complexity

O(d)

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.