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:

[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("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
}
}
[/code]

 

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 *