Wednesday 1 February 2017

Java Program that computes the sum of the digits in an integer

Code:

import java.util.*;
public class SumDigits
{
       public static void main(String[] args)
       {
            long ln;
            System.out.print("Enter an integer: ");
            Scanner s = new Scanner(System.in);
            ln = s.nextLong();
            int sum=sumDigits(ln);
            System.out.println(" Sum of the digits in " + ln + " is " +sum);
        }
     public static int sumDigits(long n)
     { 
         int a=0;
         while (n!=0)
         {
              a+=n%10;
              n=n/10;
         }
         return a;
      }
}


Output:



No comments:

Post a Comment