C++ Program to Count the Total Digits in a Number

This article provides some programs in C++ that count the total number of digits available in a number entered by the user at run-time of the program. This article deals with:

For example, if the user enters a number like 13204, the output will be 5. because there are 5 digits available in the given number.

Using the while loop, count the total digits in a number

The question is: write a C++ program that receives a number from the user and counts and prints the total number of digits available in that given number. Here is the answer to this question:

#include<iostream>

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

Here is the initial output produced by the above C++ program on counting the total number of digits available in a given number by the user at run-time:

c++ program count total digits in number

Now enter a number, say 43024, as input and press the ENTER key to see the output as shown in the snapshot given below:

count total digits in given number c++

The following is the dry run of the above program with user input 43024:

Count Digits in a Number using the for Loop

This program does the same job as the previous program. The only difference is its approach. That is, unlike the previous program, this one is written in a for loop rather than a while loop.

#include<iostream>

using namespace std;
int main()
{
   int num, tot;
   cout<<"Enter the Number: ";
   cin>>num;
   for(tot=0; num>0; tot++)
      num = num/10;
   cout<<"\nTotal Digits = "<<tot;
   cout<<endl;
   return 0;
}

This program produces the same output as the previous program.

Using a Function, Count the Digits in a Number

This is the last program on counting the total number of digits available in a number entered by the user using a user-defined function like shown in the program given below:

#include<iostream>

using namespace std;

int myfun(int);
int main()
{
   int num, tot;
   cout<<"Enter the Number: ";
   cin>>num;
   tot = myfun(num);
   cout<<"\nTotal Digits = "<<tot;
   cout<<endl;
   return 0;
}
int myfun(int n)
{
   int t;
   for(t=0; n>0; t++)
      n /= 10;
   return t;
}

C++ Quiz


« Previous Program Next Program »


Liked this post? Share it!