Java Online Compiler
Example: Sum of Digits using Recursion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Digits using Recursion import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Recursive method to calculate the sum of digits public static int sumDigitsRecursive(int number) { // Base case: If the number is 0, the sum of digits is 0 if (number == 0) { return 0; } // Recursive step: // 1. Get the last digit (number % 10) // 2. Add it to the sum of digits of the remaining number (number / 10) return (number % 10) + sumDigitsRecursive(number / 10); } public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a number System.out.print("Enter a non-negative integer: "); int num = scanner.nextInt(); // Step 3: Validate input to ensure it's non-negative if (num < 0) { System.out.println("Please enter a non-negative integer."); } else { // Step 4: Call the recursive method to calculate the sum of digits int sum = sumDigitsRecursive(num); // Step 5: Print the result System.out.println("The sum of digits of " + num + " is: " + sum); } // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS