Sum of Digits

Java program to find the sum of digits of a number

Java Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Input from user
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int sum = 0;

        // Extract digits and add to sum
        while (num != 0) {
            sum += num % 10;  // Add last digit
            num /= 10;        // Remove last digit
        }

        System.out.println("Sum of digits: " + sum);
    }
}
Output
Enter a number: 1234
Sum of digits is: 10