Sum of Digits in Java

Compute the sum of digits of a number.

BeginnerModule 3: Loop ProgramsExample 6 of 25
sum-of-digits.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int n = sc.nextInt();
8
9 int sum = 0;
10 while (n != 0) {
11 sum += n % 10;
12 n /= 10;
13 }
14
15 System.out.println("Sum of digits = " + sum);
16 sc.close();
17 }
18}

Output

Enter a number: 1234
Sum of digits = 10

What's going on

We peel digits one by one using modulo and division and add them to sum.