Problem: Write a C++ program to count the number of digits in a number.


The number of times we can divide a number by 10 is the number of digits the number has.

We repeatedly divide the number by 10 (i.e. num=num/10) until it is reduced to zero and meanwhile count the number of divisions to get the count of digits.


Enter number
Number of Digits: 4

Note: In the program, before starting the counting process we check for negative input. If the input is found negative then we have to multiply it by -1 to convert it to a positive integer.


Initially: num = 7845, count = 0

After the first iteration of while loop: num = 785, count = 1
After the second iteration of while loop: num = 78, count = 2
After the third iteration of while loop: num = 7, count = 3
After the fourth iteration of while loop: num = 0, count = 4

While loop execution end after 4th iteration because num is reduced to 0 therefore the loop condition num>0 fails. The final value of count is 4.

Leave a Reply

4 × 1 =