Sum of Digits of a Number in Java - Sum of Digits Program in Java



Sum of Digits of a Number in Java :

  • Sum of digits in a Java program allows a user to enter any number, divide that number into individual numbers, and sum those individual numbers. Ex: Given number = 123 => 1 + 2 + 3 = 6.

Sample Code

import java.util.Scanner;

public class sumofdigit 
{
  public static void main(String[] args) {
    int n, sum = 0, m;
    System.out.println("Enter a number: ");
    Scanner sc = new Scanner(System.in);
    n = sc.nextInt();
    while (n > 0) {
      m = n % 10;
      sum = sum + m;
      n = n / 10;
    }
    System.out.println("Sum is= " + sum);
  }
}

Output

Enter a number : 12345
Sum is = 15

Related Searches to Sum of Digits of a Number in Java - Sum of Digits Program in Java

is obtained