Java Online Compiler
Example: Sum of Digits using Do-While Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Digits using Do-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 user 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 originalNumber = number; // Store the original number for output // Step 4: Use a do-while loop to calculate the sum of digits // The loop continues as long as the number is not 0 do { // Get the last digit of the number int digit = number % 10; // Add the digit to the sum sum += digit; // Remove the last digit from the number number /= 10; } while (number != 0); // Step 5: Print the result System.out.println("The sum of digits of " + originalNumber + " is: " + sum); // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS