Direct count total digits in a number C++ Program

Here is a simple C++ program to count total number of digits in a number. To count digits, we use log. And for this purpose we use cmath library.

/* C++ Program to count digits in number */
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
 int num,digits;
 
 cout<<"Enter a number: ";
 cin>>num;
 
 digits=log10(num)+1;
 
 cout<<"Digits = "<<digits;
 return 0;
}

Another simple C++ program to count digits in a number

/* C++ Program to count digits in number */
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
 int num,digits=0;
 
 cout<<"Enter a number: ";
 cin>>num;
 
 while(num!=0)
 {
  digits++;
  num=num/10;
 }
 
 cout<<"Digits = "<<digits;
 return 0;
}

Popular posts from this blog