Sum of Digits

Compute the sum of digits of a number.

JavaBeginner
Java
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

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