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.
#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;
}
Enter the Number: 1230435 Total Digits = 7
Here I have explained the logic of the program step by step:
count=0
.num
.num!=0
.count++
.num/10
.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;
}
Enter the Number: 3578 Total Digits = 4
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;
}
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.