Given a number, we need to find the sum of digits in the number using recursion. In C#, recursion is a process in which a function calls itself directly or indirectly and the corresponding function is known as a recursive function. It is used to solve problems easily like in this article using recursion we will find the sum of digits of a number.
Example
Input: 456
Output: 15
Input: 123
Output: 6
Approach:
To find the sum of digits of a number using recursion follow the following approach:
- We call the SumOfDigits function with the argument n.
- In function, the last digit is retrieved by n % 10.
- The function is recursively called with argument as n / 10.[i.e. n % 10 + SumOfDigit(n / 10)]
- The function is called recursively until the n > 0.
Example 1:
C#
using System;
class GFG{
static int SumOfDigit( int n)
{
if (n == 0)
return 0;
return (n % 10 + SumOfDigit(n / 10));
}
public static void Main()
{
int n = 123;
int ans = SumOfDigit(n);
Console.Write( "Sum = " + ans);
}
}
|
Example 2:
C#
using System;
class GFG{
static int SumOfDigit( int n)
{
if (n == 0)
return 0;
return (n % 10 + SumOfDigit(n / 10));
}
public static void Main()
{
int number, res;
Console.WriteLine( "Hi! Enter the Number: " );
number = int .Parse(Console.ReadLine());
res = SumOfDigit(number);
Console.WriteLine( "Sum of Digits is {0}" , res);
Console.ReadLine();
}
}
|
Output:
Hi! Enter the Number:
12345
The Sum of Digits is 15
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Apr, 2022
Like Article
Save Article