C++ Program to find number of digits in an integer

Finding number of digits in an integer in C++

Here we will discuss how to find the number of digits in an integer in c++ programming language.

An integer is made up a number of digits i.e. a number is a combination of 0-9. Example 9825 is any integer which has 4 digits.

number of digits in an integer in C++

Method Discussed :

  • Method 1 : Using loop
  • Method 2 : Using formulae.

Let’s discuss above two methods in brief,

Method 1:

Let’s see how the code works:

  • The user will give an input.
  • The input will be stored in an int type variable say num.
  • do while loop is started
    • Divide num by 10 and store result in num itself

                                            num=num/10;

    • Every time num is divided by 10 increment digit by 1

                                            digit++;.

    • Do this until num is not equal to 0

                                            while(num!=0);

  • digit is printed which is the number of digits in num.

Method 1 : Code in C++

Run
#include<bits/stdc++.h>
using namespace std;

int main(){
    int num = 20901;
    int digit = 0;
    
    while(num>0){
        digit++;
        num = num/10;
    }
    cout<<"No. of digits = "<< digit;

}

Output

No. of digits = 5

Method 2 :

In this method we will simple use the mathematical formulae,

  • No. of digits : floor(log10(n))+1

Method 2 : Code in C++

Run
#include<bits/stdc++.h>
#include<iostream>


using namespace std;

int
main ()
{
  
int num = 20901;
  
int digit = floor (log10 (num)) + 1;
  
 
cout << "No. of digits = " << digit;

 
}

Output

No. of digits = 5