C++ Program to count Total Digits in a Number
In this example, we will write a C++ program to count the total number of digits in an integer entered by the user during run time.
Example:
Input: 3567 Output: 4
when the user input 3567 then the output will be 4.
program to count total digit in a number using while loop.
#include<iostream>
using namespace std;
int main()
{
int num, count=0;
cout<<"Enter the Number: ";
cin>>num;
while(num != 0)
{
/* Increment digit count */
count++;
/* Remove last digit of 'num' */
num = num/10;
}
cout<<"\nTotal Digits = "<<count;
return 0;
}
output
Enter the Number: 1230435 Total Digits = 7
Logic to count the Total digit in a number.
Here I have explained the logic of the program step by step:
- initialize count variable to stored total digit
count=0. - Take input from the user and stored it in variable
num. - Iterate loop until num value becomes 0 i.e
num!=0. - Inside the loop increment the count value by 1 i.e
count++. - Remove the last digit of a number i.e
num/10. - repeat steps 4 and 5 until num becomes 0 or less than 0.
using for loop
In this program, we will find all digits in an integer by using for loop.
#include<iostream>
using namespace std;
int main()
{
int num, count;
cout<<"Enter the Number: ";
cin>>num;
for(count=0 ;num != 0; num = num / 10)
{
/* Increment digit count */
count++;
}
cout<<"\nTotal Digits = "<<count;
return 0;
}
output
Enter the Number: 3578 Total Digits = 4
Program to Count Total Digit in a number without using any loop
In this program, we will count the total digit without using any loop, you can do this by using log10(num)+1.
#include<iostream>
#include <math.h>
using namespace std;
int main()
{
int num, count;
cout<<"Enter the Number: ";
cin>>num;
/* Calculate total digits */
count = (num == 0) ? 1 : (log10(num) + 1);
cout<<"\nTotal Digits = "<<count;
return 0;
}
output
Enter the Number: 123 Total Digits = 3
Let's see the explanation, of how log counts total digits by taking a simple example.
for example, in log10(100) we now it will give a value of 2 i.e log10(10)2 . it become 2log10(10) = 2. but 100 has 3 digit therefore we have add 1 in log10(num)+1.