This is a Java Program to Find 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:
<pre lang="text" cssfile="hk1_style">
$ javac Sum_Numbers.java
$ java Sum_Numbers
Enter the no. of elements you want:6
Enter all the elements you want:2
3
5
6
7
1
Sum:24
Sanfoundry Global Education & Learning Series - 1000 Java Programs.
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
advertisement
advertisement
Related Posts:
- Practice Information Technology MCQs
- Apply for Java Internship
- Check Java Books
- Practice BCA MCQs
- Apply for Computer Science Internship