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 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(); // Step 3: Initialize sum to 0 int sum = 0; int tempNumber = number; // Use a temporary variable to avoid modifying the original number // Step 4: Loop until the number becomes 0 while (tempNumber != 0) { // Step 4a: Get the last digit using the modulo operator int digit = tempNumber % 10; // Step 4b: Add the digit to the sum sum += digit; // Step 4c: Remove the last digit using integer division tempNumber /= 10; } // Step 5: Print the sum of digits System.out.println("Sum of digits for " + number + " is: " + sum); // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS