 # C++ Program to count the number of digits of a number

October 5, 2021, Learn eTutorial
887

In this C++ program, we counts the total number of digits available in a number in runtime

## How to write a C++ program to count the digits in a number?

The user is asked to enter a number. The number is read into the variable num. Now we have to count the number of digits within the entered number. Here we are using a while loop to execute the program.  Set a variable t to hold the number of digits and initially set the value of t to 0; Within the loop increment the value of t by 1. t++.

Then execute the code num = num/10; each execution of this code will remove the last digit from the variable num and simultaneously will increment the value of the variable t by 1. This will continue until the condition of the` while loop` evaluation is false. After exiting the loop, the variable t holds the value that is equal to the number of digits available in the number. Print the result.

### Algorithm

Step 1: Call the header file` iostream.`

Step 2: Use the` namespace std`.

Step 3: Open the main function; int main().

Step 4: Declare  integer type variables num, t = 0;

Step 5: Ask the user to enter a number;

Step 6: Get the number to the variable num;

Step 7: Define a while loop with condition num > 0 and count the digits of the number by using the method num = num/10; increment the value of t by 1 for each iteration

Step 8: Display the value of

Step 9: Exit

## C++ Source Code

```                                          ```#include<iostream>
using namespace std;
int main()
{
int num, t=0;
cout<<"Enter the Number: ";
cin>>num;
while(num>0)
{
t++;
num = num/10;
}
cout<<"\nTotal Digits = "<<t;
cout<<endl;
return 0;
}```
```

## OUTPUT

```Enter the Number: 564782
Total Digits = 6
```