LearnFrenzy
Sign in Take a free test

C Loops · Loop Programs · Question 5

Frequency of each digit in a number in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Count how many times each digit appears in 1223334.

Solution
main.c
#include <stdio.h>

int main(void) {
    long n = 1223334;
    int count[10] = {0};
    do {
        count[n % 10]++;
        n /= 10;
    } while (n > 0);                 /* do-while: also works for n = 0 */

    for (int d = 0; d < 10; d++)
        if (count[d] > 0)
            printf("%d:%d ", d, count[d]);
    printf("\n");
    return 0;
}

Output Verified by compiling and running

1:1 2:2 3:3 4:1

Each digit indexes a counter. do-while makes the input 0 count as one digit 0, which a while loop would miss.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links