To count the digits in a number using recursion
This program can count the number of digits in a number using recursion.
Logic:
- Get the input number from the user.
- Pass the number as an argument to the function.
- Then count the number of digits by passing number recursively by removing the last digit.
- At last return the count of the digit.
Program:
#include<stdio.h> void main() { int n; clrscr(); printf("enter the number:"); scanf("%d",&n); /*pass the number into the funtion as an argument*/ printf("total digits in the number is %d",digit(n)); getch(); } int digit(int n) { int i=0;//value of i initializes to zero for every time if(n!=0) { i++;//increments the value when n not equal to zero /* for every time the value of i becomes 1 because i initializes to zero then digit funtion runs recursively after the number decrements one digit*/ return i+digit(n/10);// } else { return 0;//returns when n becomes zero } }