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.

To find the number of digits in an integer we will use loops along with an arithmetic operator, ‘/ ’.

number of digits in an integer in C++

Algorithm :

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.
Number of digits in an integer in C++
Competitive Coding Techniques

                                                                     Code in C++

//C++ Program
//Number of Digits in an Integer

#include<iostream>
using namespace std;

int main()
{

  int num,digit=0;
  cout<<"Enter any num : ";
  //user input
  cin>>num;

  //loop to find number digits
  do
  {
    num=num/10;
    digit++;
  }while(num!=0);

  //output
  cout<<"Number of digits in the given integer is: "<<digit;
  return 0;
}
Output:
Enter any num : 12398
Number of digits in the given integer is: 5