Skip to main content

Cpp program to count digits in an integer

C++ program to count the number of digits in an integer:


Suppose you have an integer, n = 1567. The number of digits in n is 4.

Input: 1567
Output: 4

Input: 58694
Output: 5

Solution: 

To solve this problem, we can simply iterate to all these digits starting from the rightmost digit. We will update the number by dividing it by 10 until it becomes less than or equal to zero.

Step 1: n=1567, count=0.
            n = n/10; count = count+1;

Step 2: n=156, count=1.
            n = n/10; count = count+1;

Step 3: n=15, count=2.
            n = n/10; count = count+1;

Step 4: n=1, count=3.
            n = n/10; count = count+1;

Step 5: n=0; count=3;
            Loop will end here.

C++ implementation:



#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int count = 0;
    while (n != 0)
    {
        n = n / 10;
        count++;
    }
    cout << "Number of digits : " << count;
    return 0;
}



Comments