# Sum of Natural Numbers using Recursion in Java

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.

1. `import java.util.Scanner;`
2. `public class Sum_Numbers `
3. `{`
4. `    int sum = 0, j = 0;`
5. `    public static void main(String[] args) `
6. `    {`
7. `        int n;`
8. `        Scanner s = new Scanner(System.in);`
9. `        System.out.print("Enter the no. of elements you want:");`
10. `        n = s.nextInt();`
11. `        int a[] = new int[n];`
12. `        System.out.print("Enter all the elements you want:");`
13. `        for(int i = 0; i < n; i++)`
14. `        {`
15. `            a[i] = s.nextInt();`
16. `        }`
17. `        Sum_Numbers obj = new Sum_Numbers();`
18. `        int x = obj.add(a, a.length, 0);`
19. `        System.out.println("Sum:"+x);`
20. `    }`
21. `    int add(int a[], int n, int i)`
22. `    {`
23. `        if(i < n)`
24. `        {`
25. `            return a[i] + add(a, n, ++i);`
26. `        }   `
27. `        else`
28. `        {`
29. `            return 0;`
30. `        }`
31. `    }`
32. `}`
33. `Output:`
34. `<pre lang="text" cssfile="hk1_style">`
35. `\$ javac Sum_Numbers.java`
36. `\$ java Sum_Numbers`
37. ` `
38. `Enter the no. of elements you want:6`
39. `Enter all the elements you want:2`
40. `3`
41. `5`
42. `6`
43. `7`
44. `1`
45. `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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.