Java: Compute the sum of the digits of an integer
Java Basic: Exercise-33 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/basic/java-basic-exercise-33.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics