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.
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
#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;
}CURRENT STEP
SELECTED LINE
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)
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use the extracted digit as an index into a fixed ten-element frequency array.
- 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.
