Java while loop sum the digits in an integer

Question

We would like to write a program that reads an integer between 0 and 1000.

Add all the digits in the integer.

For example, if an integer is 932, the sum of all its digits is 14.

Hint

Use the % operator to extract digits

Use the / operator to remove the extracted digit.

For instance, 932 % 10 = 2 and 932 / 10 = 93.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number between 0 and 1000: ");
    int n = input.nextInt();

    System.out.println("The sum of the digits is " + sumDigits(n));
  }// w ww. ja  v  a2s  .c  om

  private static int sumDigits(int n) {
    //your code here
  }
}


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number between 0 and 1000: ");
    int n = input.nextInt();

    System.out.println("The sum of the digits is " + sumDigits(n));
  }

  private static int sumDigits(int n) {
    int sum = 0;
    while (n != 0) {
      sum += n % 10;
      n /= 10;
    }
    return sum;
  }
}



PreviousNext

Related