Sum of Digits Program in Java

Sum of Digits Program in Java
Sum of Digits Program in Java

If a number enter 5462 then sum of theses digits 5+4+6+2 = 17.


import java.util.Scanner;

public class SumofDigits
{
    public static void main(String[] args)
    {
        // TODO code application logic here
        int r, n, num,
        sum = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number=");
        n = sc.nextInt();
        num = n;
        while (num > 0)
        {
            r = num % 10;
            sum = sum + r;
            num = num / 10;
        }
        System.out.println("Sum of digit=" + sum);
    }
}

Output:

Enter number=1234
Sum of digit=10
b. tech. bca icse java java tutorials learn java mca programs

Frequently Asked Questions

If a number enter 5462 then sum of theses digits 5+4+6+2 = 17.
If a number enter 5462 then sum of theses digits 5+4+6+2 = 17.