#include <stdio.h> int C_D(int, int); int main() { int num, res; printf("\n \n Enter an integer to count number of digits in it."); printf("\n"); scanf("%d", &num); printf("Number of digits in %d is %d", num, C_D(num,0)); return 0; } int C_D(int num,int count) { if(num == 0) { return count; } return C_D(num/10,++count); }
Output: Enter an integer to count the number of digits in it. 123 Number of digits in 123 is 3
Code Analysis This code counts the number of digits in an integer. Program logic uses recursion. Program takes input from the user and divides it by 10. Each time the number is divided by 10, a variable count which keeps track of number of digits is incremented.
Leave a Reply