In this C program, we will 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.
#include<stdio.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: %d",num,count); return 0; }Output
Enter an integer 12345 Number of digits : 5
Enter an integer -345 Number of digits : 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
#include<stdio.h> #include<math.h> int main() { int num, temp; printf("Enter an integer\n"); scanf("%d", &num); temp = num; 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); } return 0; }Output
Enter an integer 6534 Number of digits in 6534 : 4
Enter an integer -423 Number of digits in -423 : 3
Related Topics