www_programiz_com_java_programming_examples_sum_natural_numb
www_programiz_com_java_programming_examples_sum_natural_numb
Java Methods
Java Recursion
The positive numbers 1, 2, 3... are known as natural numbers. The program below
takes a positive integer from the user and calculates the sum up to the given number.
You can find the sum of natural numbers using loop as well. However, you will learn to
solve this problem using recursion here.
Output
Sum = 210
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
The number whose sum is to be found is stored in a variable number .
Initially, the addNumbers() is called from the main() function with 20 passed as an
argument.
When num is equal to 0, there is no recursive call and this returns the sum of integers
to the main() function.
Related Examples
Java Example
Java Example
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Java Example
Java Example
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF