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#
// C# program to find the sum of digits of a number // using recursion using System;
class GFG{
// Method to check sum of digit using recursion static int SumOfDigit( int n)
{ // If the n value is zero then we
// return sum as 0.
if (n == 0)
return 0;
// Last digit + recursively calling n/10
return (n % 10 + SumOfDigit(n / 10));
} // Driver code public static void Main()
{ int n = 123;
int ans = SumOfDigit(n);
Console.Write( "Sum = " + ans);
} } |
Output
Sum = 6
Example 2:
C#
// C# program to find the sum of digits of a number // using recursion // Here, we take input from user using System;
class GFG{
// Method to check sum of digit using recursion static int SumOfDigit( int n)
{ // If the n value is zero then we return sum as 0.
if (n == 0)
return 0;
// Last digit + recursively calling n/10
return (n % 10 + SumOfDigit(n / 10));
} // Driver code public static void Main()
{ int number, res;
// Taking input from user
Console.WriteLine( "Hi! Enter the Number: " );
number = int .Parse(Console.ReadLine());
res = SumOfDigit(number);
// Displaying the output
Console.WriteLine( "Sum of Digits is {0}" , res);
Console.ReadLine();
} } |
Output:
Hi! Enter the Number: 12345 The Sum of Digits is 15
Article Tags :