Write a Java Program to find the sum of natural numbers using recursion.
Click Here to View the Solution!
public static void main(String args)
sum = addNumbers(number);
System.out.println("Sum = "
public static int addNumbers(int num)
num + addNumbers(num -1
Click Here to View the Output!
Sum = 465
Click Here to View the Explanation!
- This program in used to calculate the sum of the natural numbers till a given
numberthrough the process of recursion.
- An integer number 30 is initialized in the program. All the natural numbers up to 30 will be added into the variable sum using the user-defined function
addNumbersthat is called from main().
- In the first step, the number 30 will be added into the output of
- As a recursive function,
addNumbers()will be called by
addNumbers()and 29 will be passed and added to the output of
addNumbers(28). This recursive process will continue until the number reaches 0.
- After the number becomes equal to 0, the recursive call will end and the sum of all the natural numbers will be stored in the variable
sumand returned to the
main()function to be printed.