Write a Java program and compute the sum of the digits of 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. public static void main(String[] args) {
  4. Scanner input = new Scanner(System.in);
  5. System.out.print("Enter an integer: ");
  6. long n = input.nextLong();
  7. System.out.println("The sum of the digits is: " + sumDigits(n));
  8.  
  9. }
  10.  
  11. public static int sumDigits(long num) {
  12. int sum = 0;
  13. while (num != 0) {
  14. sum += num % 10;
  15. num /= 10;
  16. }
  17. return sum;
  18. }
  19. }

Result

java techstudy.org

     





Related Topics




Popular Posts