使用递归查找数字的数字和的 C# 程序
给定一个数字,我们需要使用递归找到数字中的数字总和。在 C# 中,递归是一个函数直接或间接调用自身并且相应的函数称为递归函数的过程。它用于轻松解决问题,如本文中使用递归我们将找到数字的数字总和。
例子
Input: 456
Output: 15
Input: 123
Output: 6
方法:
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.
示例 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);
}
}
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();
}
}
输出
Sum = 6
示例 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();
}
}
输出:
Hi! Enter the Number:
12345
The Sum of Digits is 15