codescracker
c++

C++ Program to Count Total Digits in a Number



« C++ Tutorial C++ Example »

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

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

Count Total Digits in a Number using while Loop

The question is, write a C++ program that receives a number from user to count and print 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 above C++ program on counting total number of digits available in a given number by user at run-time:

c++ program count total digits in number

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

count total digits in given number c++

The dry run of above program with user input 43024 goes like:

Count Digits in a Number using for Loop

This program does the same job as of previous program. The only difference is its approach. That is, this program is created using for loop instead of while as done in previous program.

#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 same output as of previous program.

Count Digits in a Number using Function

This is the last program on counting the total number of digits available in a number entered by 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++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker