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:

#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
	}
}

You might also like:

 To find the power of number using recursion

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

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.
0 0 votes
Article Rating
Subscribe
Notify of
guest
5.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5.4K
0
Would love your thoughts, please comment.x
()
x