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

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

Dividing the number by 10 i.e num = num/10 means removing the last digit from the number.

But before that, we need to check for negative integers. 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.

Comment below if you have any doubts or suggestions.

Leave a Reply