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?

Thanks!

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.

Use the mod (%) opreator followed by the divide (/) operator to check each digit.

Vernon,

It works! Thank you very much! =D

WaltP,

Thank you as well :icon_cheesygrin:

You can do it efficiently by using 'BIT WISE OPERATORS'. Bitwise operators help a lot in such problems!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.