Sum of digits of a number in java

Java code to add all digits of a numbers 


import java.io.*;

class Test {
     public static void main(String[] args) throws IOException {
         
          int num,sum=0,r;
          System.out.println("Enter a number:");
          BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
          num=Integer.parseInt(br.readLine());

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

          System.out.println("sum= "+sum);
     }
}

No comments: