Friday, 17 June 2016

Program to find the Sum of digits of a Given Number until a Single digit is obtained.

Explanation :
1) If n=12 then output will be 1+2=3.
2) If n=78 then output will be 7+8=15 which will further proceed to give the result as 1+5=6.

Code:

import java.util.Scanner;
public class SumOfDigits
{
    public static void main(String[] args)
    {    
         int sum=0,rem=0;
         Scanner sc=new Scanner(System.in);
         System.out.println("Enter any Number:");
         int n=sc.nextInt();
          while(n > 0)
          {
                     while(n != 0)
                     {
                          rem = n%10;
                          sum = sum+rem;
                          n=n/10;
                     }
                     if(sum > 9)
                     {
                            n = sum;
                            sum = 0;
                     }
           }
          System.out.println("Sum: "+sum);
          sc.close();
    }  
}

No comments:

Post a Comment