C Program To Count Frequency of Digits in A Given Number
C Program To Count Frequency of Digits in A Given Number
C Program To Count Frequency of Digits in A Given Number
Example:
Input num: 116540
Output:
Frequency of 0 = 1
Frequency of 1 = 2
Frequency of 2 = 0
Frequency of 3 = 0
Frequency of 4 = 1
Frequency of 5 = 1
Frequency of 6 = 1
Frequency of 7 = 0
Frequency of 8 = 0
Frequency of 9 = 0
Required knowledge
Basic C programming, Loop, Array
Here goes the step-by-step detailed explantion about how you gonna find the
frequency of digits in an integer.
First of all we need a storage where we can store frequencies of each digits. For
that we will be using an integer array of size 10 call it as freq[10]. We have used
an array of size 10 because decimal has base 10. There are only 10 digits that
makes up any decimal number.
Next, we need to initialize every element of the array with 0. Assuming that every
digit has occurred 0 times.
Now comes the main logic. Find the last digit of the given number. For that we need
to perform modular division by 10 i.e. lastDigit = num % 10 (where num is the
number whose frequency of digits is to be found).
Increment the freq[ lastDigit ]++ by one.
Now remove the last digit from the num as it isn't needed anymore. Perform num =
num / 10.
Repeat steps 3-5 till num != 0. Finally you will be left with an array freq having
the frequency of each digits in that number.
Lets, now implement this on code.
/**
* C program to count frequency of digits in a given number
*/
#include <stdio.h>
#define BASE 10
int main()
{
long long num, n;
int i, lastDigit;
int freq[BASE];
while(n != 0)
{
// Gets the last digit
lastDigit = n % 10;
return 0;
}