Posted by Somesh Shinde
 
On 
Wednesday, 29 June 2016
 
Sum of Digits
| 
Logic: 513 -> 5+1+3=9
| n | res | n | sum |  | 513 |  |  | 0 |  | 513%10 | 3 |  | 3 |  | 513/10 |  | 51 | 3 |  |  |  |  |  |  | 51%10 | 1 |  | 4 |  | 51/10 |  | 5 | 4 |  |  |  |  |  |  | 5%10 | 5 |  | 9 |  | 5/10 |  | 0 | 9 |  
 
| Program | Output |  | //Note: Scanner class work with JDK1.5 or above
import java.util.*;
class SumDigits
{
 public static void main(String args[])
 {  
  int n, res;
  Scanner scan= new Scanner(System.in);
  System.out.println("Please Enter No.: ");
  n1=scan.nextInt();
  while(n>0)
  {
   res=n%10;
   n=n/10;
   sum+=res; //sum=sum+res;
  }
  System.out.println("Second No: " + n2);
 }
}
       | Please Enter No 1: 10
Please Enter No 2: 5
First No: 5
Second No: 10
     |  | 
 
 
 
 
0 comments:
Post a Comment