Java Online Compiler
Example: Sum of Digits using Modulo and Division in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Digits using Modulo and Division import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get input number from the user System.out.print("Enter a non-negative integer: "); int number = scanner.nextInt(); // Step 2: Initialize sum int sum = 0; // Step 3: Loop until the number becomes 0 int tempNumber = number; // Use a temporary variable to preserve original number while (tempNumber != 0) { // Get the last digit int digit = tempNumber % 10; // Add the digit to sum sum += digit; // Remove the last digit tempNumber /= 10; } // Step 4: Print the result System.out.println("The sum of digits of " + number + " is: " + sum); scanner.close(); } }
Output
Clear
ADVERTISEMENTS