Find the Sum of Digits of a number.
Question : Find the sum of digits of a number
Suppose we have a number and we need to find the sum of digits of the number. e.g let the number be 456789, then the sum of digits will be 4 + 5 + 6 + 7 + 8 + 9 = 39
import java.util.Scanner;

class FindSum{

 public static void main(String args[]){

 System.out.println("Enter the number");
 Scanner sc = new Scanner(System.in);
 FindSum object = new FindSum();
 int number = sc.nextInt();
 int sum = object.findSumOfDigits(number);
 System.out.println("Sum of digits of "+number+" = "+ sum);
 }

 public int findSumOfDigits(int num){

  int sum = 0;
  while(num != 0){
    sum += num % 10;
    num = num / 10;  
  }
  return sum;
 }

}
Enter the number
456789
Sum of digits of 456789 = 39
In the above program we take the number as input from the user by using the Scanner class and then pass this number to the method findSumOfDigits() that calculates the sum of digits of the number.

The while loop runs till the number is not zero. In the while loop we add the last digit of the number to the sum and divide the number by 10. What happens is

sum += 456789 % 10(gives 9), so sum = 0 + 9 = 9 and num = 456789 / 10 = 45678 (since num is integer)
sum += 45678 % 10(gives 8), so sum = 9 + 8 = 17 and num = 45678 / 10 = 4567
and so on.

No comments :

Post a Comment