Recursive Array Sum

Lab Java Beginner 10 points

Write static int sum(int[] a, int i) that returns the sum of a[i..] recursively.

Input

Line 1: n. Line 2: n integers.

Output

The sum.

Example

Input

5
1 2 3 4 5

Output

15
Sample input available Sample output available
Editor
Java

Hints

Pass the current index; stop when it reaches the end.

Solution explanation

Recursion over arrays usually carries an index instead of making smaller copies.

Show solution
import java.util.Scanner;

public class Main {
    static int sum(int[] a, int i) {
        if (i == a.length) {
            return 0;
        }
        return a[i] + sum(a, i + 1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        System.out.println(sum(a, 0));
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD