Java Online Compiler
Example: Sum of Natural Numbers (Recursive) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Natural Numbers (Recursive) import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Recursive method to calculate the sum of natural numbers public static int sumNaturalNumbers(int n) { // Step 1: Define the base case // If n is 0, the sum is 0. This stops the recursion. if (n == 0) { return 0; } // Step 2: Define the recursive step // Sum of n natural numbers = n + sum of (n-1) natural numbers else { return n + sumNaturalNumbers(n - 1); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 3: Prompt user for input System.out.print("Enter a positive integer (n): "); int n = scanner.nextInt(); // Step 4: Validate input if (n < 0) { System.out.println("Please enter a non-negative integer."); } else { // Step 5: Call the recursive method int sum = sumNaturalNumbers(n); // Step 6: Display the result System.out.println("The sum of natural numbers up to " + n + " is: " + sum); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS