To count the digits in a number using recursion

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:

[code lang=”c”]
#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
}
}
[/code]

You might also like:

 To find the power of number using recursion

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

Your email address will not be published. Required fields are marked *