Java Online Compiler
Example: Sum of Digits using While Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Digits using While Loop import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read input from the user Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a number System.out.print("Enter a number: "); int number = scanner.nextInt(); // Read the integer input // Step 3: Initialize a variable to store the sum of digits int sumOfDigits = 0; // Step 4: Use a while loop to extract and sum digits // The loop continues as long as the number is greater than 0 while (number > 0) { // Step 4a: Get the last digit using the modulo operator (%) int digit = number % 10; // Step 4b: Add the extracted digit to the sum sumOfDigits += digit; // Step 4c: Remove the last digit from the number using integer division (/) number /= 10; // Equivalent to number = number / 10; } // Step 5: Print the final sum of digits System.out.println("Sum of digits: " + sumOfDigits); // Step 6: Close the scanner to prevent resource leaks scanner.close(); } }
Output
Clear
ADVERTISEMENTS