Write a Java method to compute the sum of the digits in an integer


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise {
  3.  
  4. public static void main(String[] args)
  5. {
  6. Scanner in = new Scanner(System.in);
  7. System.out.print("Enter an integer: ");
  8. int digits = in.nextInt();
  9. System.out.println("The sum is Digit is: " + sumDigits(digits));
  10. }
  11.  
  12. public static int sumDigits(long num) {
  13. int result = 0;
  14.  
  15. while(num > 0) {
  16. result += num % 10;
  17. num /= 10;
  18. }
  19.  
  20. return result;
  21. }
  22.  
  23. }

Result

java techstudy.org

     





Related Topics




Popular Posts