- Write a C program to count digits of a number.
Given an integer N, we have to count the number of digits of N and print it on screen.
For Example
Number of digits in 423536 is 6.
C program to count the number of digits in a number using loop
In this program, we first take a number as input from user using scanf function. Then inside while loop, we keep on removing right most digit(Least significant digit) of number and increment a counter(count variable) till number becomes zero. Finally, we print the value of count variable on screen.
/* * C program to count tne number of digits in an integer */ #include<stdio.h> #include<conio.h> int main() { int num, temp, count=0; printf("Enter an integer\n"); scanf("%d", &num); temp = num; while(temp!=0) { temp = temp/10; ++count; } printf("Number of digits in %d : %d",num, count); getch(); return 0; }
Program Output
Enter an integer 12345 Number of digits in 12345 : 5
Enter an integer -345 Number of digits in -345 : 3
C program to count the number of digits in a number using logarithm
We can use log10(logarithm of base 10) to count the number of digits of positive numbers (logarithm is not defined for negative numbers).
Digit count of N = log10(N) + 1
/* * C program to count the number of digits in an integer using logarithm */ #include<stdio.h> #include<conio.h> #include<math.h> int main() { int num, temp; printf("Enter an integer\n"); scanf("%d", &num); temp = num; /*If input number is negativ ethen make it positive */ if(temp < 0) temp = temp*-1; if(temp) { /* If input number is non-zero */ printf("Number of digits in %d : %d",num, (int)log10(temp)+1); } else { printf("Number of digits in %d : %d",num, 1); } getch(); return 0; }
Program Output
Enter an integer 6534 Number of digits in 6534 : 4
Enter an integer -423 Number of digits in -423 : 3