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

Example:

Input  :  249
Output :  3

Input  :  7500
Output :  4

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.

#include <iostream>
using namespace std;
 
int main()
{
    int num, count=0;
    
    cout <<"Enter number \n";
    cin >> num;
    
    //If number is -ve, convert it to +ve
    if(num<0)
        num=num*-1;
    
    while(num>0){
        num=num/10;
        count++;
    }
    
    cout <<"Number of Digits: " << count;
    return 0;
}

Output:

Enter number
7845
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.

Explanation:

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