Thursday, 16 June 2016

Program to find the Sum Of Digits of a given Number.

Explanation :
If number = 123 then Output will be 1+2+3=6.

Code:

import java.util.*;
public class SumOfDigits
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a number to calculate sum of digits");
         int number = sc.nextInt();
         int sum = 0;
         int input = number;
         while (input != 0)
       {
           int lastdigit = input % 10;
           sum += lastdigit;
           input /= 10;
       }
          System.out.printf("Sum of digits of number %d is %d", number, sum);
          sc.close();
     }
}

No comments:

Post a Comment