C++ Program to Count Number of Digits in an Integer

In this post, you will learn how to Count Number of Digits in an Integer using C++ programming language.

This lesson will teach you how to count the number of digits in a number, with a while loop, increment operator and mathematical functions  using the C++ Language. Let’s look at the below source code.

How to Count Number of Digits in an Integer?


Source Code

#include <iostream>
using namespace std;
int main() 
    int num, temp;
    int count = 0;
    cin >> num;
    cout << "Enter any number : "<<num<<endl;
    temp = num;
    while(temp != 0) 
        temp /= 10;
    cout << "/nTotal digits in " <<num<< " is : " <<count;
    return 0;




Enter any number : 23456
Total digits in 23456 is : 5

The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.

  1. Declare the variables int, temp, count as integers and assign the value 0 for the integer count
  2. Get the value and store it in int  and display the output statement using cout<< and the Insertion Operators'<<‘ .
  3. Using the assignment operator =’, we assign the value in int to temp.
  4. We create a while loop  with the condition (temp != 0)where the value of temp should not be equal to 0.
  5. When this condition is satisfied the loop statement is executed where the count with the initial value 0 is incremented  and then the mathematical expression temp /= 10is executed
  6. In the mathematical function when the number is divided by ten when turns the number into a decimal number and the number after the decimal point is neglected.
  7. Then the while loop is executed continuously until the condition is false and each time the loop is executed the number is reduced slowly and the count value is incremented.
  8. After the execution is completed the answer is displayed with an output statement.

Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.