Hello everyone!

I have a specific C question that I have not been able to solve.

How do you count the number of particular numbers inside an integer variable?

For example:

int variable;

The user inputs 22222 into the variable.

The program displays "You entered five twos".

How do you do this without using arrays and that the user needs to enter 22222 at once?


How about setting up a counter, initialize the counter to 0, then using a while loop? Each pass through the while loop could calculate the integer mod 10. If that result is 2 (or whatever digit you're counting), increment the counter. If not, don't increment the counter. Regardless, divide the integer by 10 in each pass through the loop to get rid of the least significant digit. When the integer is zero, bail out of the while loop. The counter variable will contain the number of 2's.


It works! Thank you very much! =D


Thank you as well :icon_cheesygrin:

This question has already been answered. Start a new discussion instead.