To find the sum of digits using recursion

To find the sum of digits using recursion

This program returns the sum of digits in a number using recursion.

Logic:

  • Get the number from the user.
  • Then pass the number as an argument to a function.
  • And separate the digits in the number and add the digits.
  • Return the sum value.

Algorithm:

  1. Get the number from the user.
  2. Then pass the number to a function to implement recursion.
  3. Take modulo division of the number.
  4. Then pass the number recursively after dividing the number by 10.
  5. At last returns the sum of digits.

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("sum of digits is: %d",digit(n));
	getch(); 
}
int digit(int n)
{
	if(n!=0)
	{
		/* take modulo division of the number and then pass the number
		 recursively after dividing the number 10 */
		return (n%10)+digit(n/10);
	}
	else
	{
		return 0;//returns 0 when value of n becomes 0
	}
}

 

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
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x