Java Online Compiler
Example: Sum of Digits using For Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Digits using For 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 a variable to store the sum of digits int sumOfDigits = 0; // Step 4: Use a for loop to extract and sum digits // The loop continues as long as the number is greater than 0 for (; number > 0; number /= 10) { // Get the last digit using the modulo operator int digit = number % 10; // Add the digit to the sum sumOfDigits += digit; } // Step 5: Print the sum of digits System.out.println("Sum of digits: " + sumOfDigits); // Step 6: Close the scanner to prevent resource leaks scanner.close(); } }
Output
Clear
ADVERTISEMENTS