📜  使用递归的数组元素之和

📅  最后修改于: 2022-05-13 01:57:51.783000             🧑  作者: Mango

使用递归的数组元素之和

给定一个整数数组,使用递归求数组元素的总和。
例子:

Input : A[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6

Input : A[] = {15, 12, 13, 10}
Output : 50

我们在下面的帖子中讨论了迭代解决方案。
给定数组中元素的总和
在这篇文章中,讨论了递归解决方案。

C++
// C++ program to find sum of array
// elements using recursion.
#include 
 
// Return sum of elements in A[0..N-1]
// using recursion.
int findSum(int A[], int N)
{
    if (N <= 0)
        return 0;
    return (findSum(A, N - 1) + A[N - 1]);
}
 
// Driver code
int main()
{
    int A[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(A) / sizeof(A[0]);
    printf("%dn", findSum(A, N));
    return 0;
}


Java
// Java program to find sum of array
// elements using recursion.
 
class Test {
    static int arr[] = { 1, 2, 3, 4, 5 };
 
    // Return sum of elements in A[0..N-1]
    // using recursion.
    static int findSum(int A[], int N)
    {
        if (N <= 0)
            return 0;
        return (findSum(A, N - 1) + A[N - 1]);
    }
 
    // Driver method
    public static void main(String[] args)
    {
        System.out.println(findSum(arr, arr.length));
    }
}


Python3
# Python program to find sum of array
# elements using recursion.
 
 # Return sum of elements in A[0..N-1]
 # using recursion.
def _findSum(arr, N):
     if len(arr)== 1:
        return arr[0]
     else:
        return arr[0]+_findSum(arr[1:], N)
 
# driver code
arr =[]
# input values to list
arr = [1, 2, 3, 4, 5]
  
# calculating length of array
N = len(arr)
  
ans =_findSum(arr,N)
print (ans)
  
# This code is contributed by Khare Ishita


C#
// C# program to find sum of array
// elements using recursion.
using System;
 
class Test {
     
    static int []arr = {1, 2, 3, 4, 5};
 
    // Return sum of elements in
    // A[0..N-1] using recursion.
    static int findSum(int []A, int N)
    {
        if (N <= 0)
            return 0;
        return (findSum(A, N - 1) + A[N - 1]);
    }
 
    // Driver Code
    public static void Main()
    {
        Console.Write(findSum(arr, arr.Length));
    }
}
 
// This code is contributed by Nitin Mittal.


PHP


Javascript


输出:

15

上述递归解决方案如何工作?