top of page
Search

# Program: Find the sum of N Numbers using recursion

Enter the number of elements you want and then enter all the required elements as an input. Now we pass all the elements along with the length of array and a zero to new function where we find sum of all the given numbers with the help of recursion.

Here is the source code of the Java Program to Find Sum of N Numbers using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

```import java.util.Scanner;
public class Sum_Numbers
{
int sum = 0, j = 0;
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the no. of elements you want:");
n = s.nextInt();
int a[] = new int[n];
System.out.print("Enter all the elements you want:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
Sum_Numbers obj = new Sum_Numbers();
int x = obj.add(a, a.length, 0);
System.out.println("Sum:"+x);
}
int add(int a[], int n, int i)
{
if(i < n)
{
return a[i] + add(a, n, ++i);
}
else
{
return 0;
}
}
}```

### Output:

```Enter the no. of elements you want:4
Enter all the elements you want:1
3
2
5
Sum:11```

Source: sanfoundry

The Tech Platform