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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!