Sum of digits of a number

Below program shows how to find out sum of each digit in the given number logic. For example, if the number is 259, then the sum should be 2+5+9 = 16.



PROGRAM
import java.util.Scanner;

class SumOfDigits {

 public static void main(String[] args) {

  int num, sum=0;
  Scanner input = new Scanner(System.in);
  
  System.out.print("Enter the number :: ");
  num = input.nextInt();
  
  while(num > 0) {
   
   sum = sum + (num % 10);
   num = num / 10;
  }
  
  System.out.println("Sum of digits is :: " + sum);
 }

}
OUTPUT 1
C:\>javac SumOfDigits.java
C:\>java SumOfDigits
Enter the number :: 123
Sum of digits is :: 6
OUTPUT 2
C:\>javac SumOfDigits.java
C:\>java SumOfDigits
Enter the number :: 456
Sum of digits is :: 15

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative