Digit Frequency hackerrank solution

      
          #include <stdio.h>
          int main() {
              int num;
              scanf("%d", &num);
          
              int frequency[10] = {0};  // Array to store digit frequency
          
              while (num > 0) {
                  int digit = num % 10;
                  frequency[digit]++;
                  num /= 10;
              }
          
              for (int i = 0; i < 10; i++) {
                  printf("%d ", frequency[i]);
              }
          
              return 0;
          }
                       
            

Let's go through the solution step by step:

We include the header file to use the standard input/output functions.

In the main() function, we declare an integer num to store the input number.

We use the scanf() function to read the input number from the user and store it in the variable num.

We declare an integer array frequency of size 10 to store the frequency of each digit. We initialize all elements of the array to 0.

We use a while loop to iterate as long as the num is greater than 0. Inside the loop, we perform the following steps:

a. We calculate the rightmost digit of num using the modulus operator % with 10. This gives us the digit at the ones place.

b. We increment the frequency of the digit by accessing the corresponding index in the frequency array: frequency[digit]++.

c. We divide the num by 10 to remove the rightmost digit and move to the next digit.

After counting the frequency of each digit, we use a for loop to iterate from 0 to 9, representing the possible digits. Inside the loop, we use the printf() function to print the frequency of each digit, separated by a space.

By providing the expected input and executing the code, you should see the frequency of each digit printed according to the problem statement on HackerRank.