Java: Compute the sum of the digits of an integer
Sum of Digits
Write a Java program and compute the sum of an integer's digits.
Test Data:
Input an intger: 25
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to input an integer
System.out.print("Input an integer: ");
// Read the integer from the user
long n = input.nextLong();
// Calculate and display the sum of the digits
System.out.println("The sum of the digits is: " + sumDigits(n));
}
public static int sumDigits(long n) {
int sum = 0;
// Calculate the sum of the digits
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
Explanation:
In the exercise above -
- It uses the Scanner class to obtain input from the user.
- First, it prompts the user to input an integer using System.out.print("Input an integer: ") and reads the input into the variable 'n'.
- It then calls a separate method named "sumDigits()" and passes the input integer n as an argument.
- Inside the "sumDigits()" method:
- It initializes an integer variable 'sum' to store the sum of the digits, starting with 0.
- It enters a while loop that continues as long as 'n' is not equal to 0.
- Inside the loop, it calculates the last digit of 'n' using the modulus operator (n % 10) and adds it to the 'sum' variable.
- It then removes the last digit from 'n' by dividing it by 10 (n /= 10).
- This process continues until all digits of the original number have been processed.
- Finally, it returns the 'sum' containing the sum of the digits.
- Finally, back in the "main()" method, it prints the result of the "sumDigits()" method, displaying the sum of the digits of the entered integer.
Sample Output:
Input an intger: 25 The sum of the digits is: 7
Flowchart:
Java Code Editor:
Previous: Write a Java program to compare two numbers.
Next: Write a Java program to compute the area of a hexagon.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics