Java program to find the sum of natural numbers using recursion
Sure, here's a Java program to find the sum of natural numbers using recursion:
refer to:theitroad.compublic class SumOfNaturalNumbers { public static void main(String[] args) { int n = 10; int sum = calculateSum(n); System.out.println("Sum of natural numbers from 1 to " + n + " = " + sum); } public static int calculateSum(int n) { if (n == 1) { return 1; } else { return n + calculateSum(n - 1); } } }
In this program, we first define an integer n
to represent the upper limit of the natural numbers to sum. We then call the calculateSum
method with n
as input.
The calculateSum
method is a recursive method that takes an integer n
as input and returns the sum of the natural numbers from 1 to n
.
If n
is equal to 1, we simply return 1, which is the base case of the recursion. Otherwise, we return n
plus the sum of the natural numbers from 1 to n-1
, which is calculated by calling calculateSum(n - 1)
recursively.
Finally, we print out the sum of the natural numbers from 1 to n
.
Note that recursive functions can be less efficient than iterative functions for large values of n
, as they require more memory and computational resources. However, recursion can be a useful tool for solving problems that have a natural recursive structure.