We can find out number of digits used in a number by using strlen string function. Before that we have to convert the number into string by strintf . Here is the sample code to display number of digits used.
#include <stdio.h>
#include <string.h>
int main(void){
char var[20];
int num;
printf("Enter a number ");
scanf("%d",&num);
sprintf(var,"%d", num);
printf(" number of digits = %d", strlen(var));
return 0;
}
If you input 2341 the output will be 4
for 0342 the output will be 3
Example: Recursive Function to Count Digits
#include <stdio.h>
int countDigits(int num) {
if (num == 0)
return 0;
return 1 + countDigits(num / 10);
}
int main() {
int number = 12345;
printf("Number of digits: %d\n", countDigits(number));
return 0;
}
Output
Number of digits : 5
Example: Counting Even and Odd Digits
#include <stdio.h>
int main() {
int num = 123456, even = 0, odd = 0;
while (num != 0) {
int digit = num % 10;
if (digit % 2 == 0)
even++;
else
odd++;
num /= 10;
}
printf("Even digits: %d, Odd digits: %d\n", even, odd);
return 0;
}