In the previous article, we have seen Java Program to generate a sequence of random numbers
In this article we are going to see how to find sum of digits of a number using Java programming language.
Java Program to Find Sum of Digits of a Number
As we know dividing any number by 10, the remainder always gives the unit place digit. The number will be reduced to zero after we exhausted all its digits. We will use this theory to get our output.
Example:
528= 5+2+8 = 15 3491= 3+4+9+1= 17 12= 1+2= 3 80451= 8+0+4+5+1 = 18
Let’s see different ways to find sum of digits of a number.
- By Using Modulo Operator and Number is Integer Value
- By Using Modulo Operator and Number is Numeric String Value
Method-1: Java Program to Find Sum of Digits of a Number By Using Modulo Operator and Number is Integer Value
Approach:
- Create Scanner class object.
- Ask user to enter the number.
- Declare a variable sum = 0 to store the sum of the digits.
- Use the modulo operator to obtain the unit place digit and add it to sum.
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner class object Scanner sc = new Scanner(System.in); // taking input from user System.out.print("Enter a number: "); int n = sc.nextInt(); // calling method to find sum of digits int sum = findSum(n); // printing sum of digits System.out.println("Sum of each digit of the number: " + sum); } //user defined method //to find sum of each digits of a number private static int findSum(int n) { // variable to store sum int sum = 0; while (n > 0) { // extracting last digit and adding to sum sum += n % 10; n /= 10; } return sum; } }
Output: Enter a number: 3476 Sum of each digit of the number: 20
Method-2: Java Program to Find Sum of Digits of a Number By Using Modulo Operator and Number is Numeric String Value
Approach:
- Use the
Integer.parseInt()
method to covert the numeric string into an integer. - Declare a variable
sum=0
to store the sum of the digits. - Use the modulo operator to obtain the unit place digit and add it to sum.
Program:
public class Main { public static void main(String[] args) { String num = "12345"; //calling method to find sum of digits int sum = findSum(num); //printing sum of digits System.out.println("Sum of each digit of the number: " + sum); } //user defined method private static int findSum(String num) { //convert numeric string into int type int n = Integer.parseInt(num); //variable to store sum int sum = 0; while (n > 0) { //extracting last digit and adding to sum sum += n % 10; n /= 10; } return sum; } }
Output: Sum of each digit of the number: 15
Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output
Related Java Programs: