Sum of Digits
Compute the sum of digits of a number.
BeginnerTopic: Module 3: Loop Programs
Java Sum of Digits Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Sum of digits = " + sum);
sc.close();
}
}Output
Enter a number: 1234 Sum of digits = 10
Understanding Sum of Digits
We peel digits one by one using modulo and division and add them to sum.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.