Q7. Write a code to count the number of digits in a number
A number is a mathematical object used to count, measure, and label. For eg 4, 5, 12, etc are numbers. Our task is to count the number of digits in the given number. Here we will see its algorithm and program. Let us understand the question with the help of an example.
For Example :- Suppose an input number is given as 4523 then the output will be 4 as there are 4 digits in the given number and digits are 4, 5, 2, 3,
Input :- 4523
Output :- 4
There is Following Algorithm for count the number of digits in a given number
START
step 1 : Input a number from user. Store it in some variable say num.
step 2 : Initialize another variable to store total digits say digit = 0.
step 3 : If num > 0 then increment count by 1 i.e. count++.
step 4 : Divide num by 10 to remove last digit of the given number i.e. num = num / 10.
step 5 : Repeat step 3 to 4 till num > 0 or num != 0.
STOP
There is Following Code for count the number of digits in a given number
#include <stdio.h>
int count_digit(long long num)
{
int count = 0;
while (num != 0) {
num = num / 10;
++count;
}
return count;
}
// Driver code
int main(void)
{
long long num = 54214247;
printf(“Number of digits : %d”,
count_digit(num));
return 0;
}
#include <iostream>
using namespace std;
int count_digit(long long num)
{
int count = 0;
while (num != 0) {
num = num / 10;
++count;
}
return count;
}
// Driver code
int main(void)
{
long long num = 21012042;
cout << “Number of digits : “
<< count_digit(num);
return 0;
}
class LFC {
static int count_digit(long num)
{
int count = 0;
while (num != 0) {
num = num / 10;
++count;
}
return count;
}
/* Driver program to test above function */
public static void main(String[] args)
{
long num = 25784587;
System.out.print(“Number of digits : ” + count_digit(num));
}
}
def count_digit(num):
count = 0
while num != 0:
num //= 10
count+= 1
return count
# Driver Code
num = 54789642
print (“Number of digits : % d”%(count_digit(num)))
function count_digit($num)
{
$count = 0;
while ($num != 0)
{
$num = round($num / 10);
++$count;
}
return $count;
}
// Driver code
$num = 58796420;
echo “Number of digits : “
. count_digit($num);
Output
Number of digits : 8
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number