C Program to Count Digits of a Number using Recursion
Write a C program to count digits of a number using recursion.
- Take an integer input from the user and handle the special case when the number is 0.
- Convert the number to positive if it's negative to simplify digit counting.
- Use the recursion function countDigits() to count digits by dividing the number by 10 repeatedly.
- Return the count by adding 1 at each recursion level until the base case (n == 0) is reached.
Example : pgm.c
#include <stdio.h> // Recursion function to count digits int countDigits(int n) { if (n == 0) return 0; return 1 + countDigits(n / 10); } int main() { int num; printf("Enter an integer: "); scanf("%d", &num); if (num == 0) { printf("Number of digits: 1\n"); } else { // Handle negative numbers if (num < 0) num = -num; printf("Number of digits: %d\n", countDigits(num)); } return 0; }
Output :
Enter an integer: 12345
Number of digits: 5
Number of digits: 5