- Java program to compute sum of digits
- Java Program to Compute Sum of Digits and Product of Digits using while loop
- Java Program to Compute Sum of Digits and Product of Digits using for loop
- Java Programming Computes Sum of Digits and Product of Digits using do while loop
- Sum of Digits of a Number in Java
- Steps to Find the Sum of Digits of a Number in Java
- Approaches to find Sum of Digits of a Number in Java
- Approach 1: Sum of Digits of a Number in Java By using for loop
- Approach 2: Sum of Digits of a Number in Java By using Function
- Approach 3: Sum of Digits of a Number in Java By using Recursion
- FAQ related to Sum of Digits of a Number in Java
- Sum of Digits of a Number in Java
- Introduction
- Steps to Find the Sum of Digits of a Number in Java
- By using for loop
- By using Function
- By using Recursion
- By using Command Line Arguments
- Conclusion
- Sum of Digits of a Number in Java
- Using while loop
- Sum of Digits of a Number in Java using for loop
- Sum of digits in Java without using the loop
Java program to compute sum of digits
This simple java program is used to compute the sum of digits for the given number as user input.
import java.util.Scanner; class SumOfDigits < public static void main(String arg[]) < long n,sum; Scanner sc=new Scanner(System.in); System.out.println("Enter a number "); n=sc.nextLong(); for(sum=0 ;n!=0 ;n/=10) < sum+=n%10; >System.out.println("Sum of digits of a number is "+sum); > >E:\Java-app>javac SumOfDigits.java E:\Java-app>java SumOfDigits Enter a number 4567 Sum of digits of a number is 22Java Program to Compute Sum of Digits and Product of Digits using while loop
This java program is used to calculate the sum of digits for the given number as user input.
This java program is also used to calculate the product of the digits for the given number as user input.
import java.util.Scanner; public class Digits < public static void main(String args[]) < Scanner in = new Scanner(System.in); System.out.println("Digits Sum and Product"); System.out.println("-----------------------"); System.out.print("Enter Number: "); int number = in.nextInt(); int remainder, temp, sum=0, product=1; temp = number; while (temp!=0)< remainder = temp % 10; sum = sum + remainder; product = product * remainder; temp = temp / 10; >System.out.println("Sum of digits of Number '"+number+"'': "+sum); System.out.println("Product of digits of Number '"+number+"'': "+product); > >D:\Java_Programs>javac Digits.java D:\Java_Programs>java Digits Digits Sum and Product ----------------------- Enter Number: 153 Sum of digits of Number '153'': 9 Product of digits of Number '153'': 15Java Program to Compute Sum of Digits and Product of Digits using for loop
import java.util.Scanner; public class Digits < public static void main(String args[]) < Scanner in = new Scanner(System.in); System.out.println("Digits Sum and Product"); System.out.println("-----------------------"); System.out.print("Enter Number: "); int number = in.nextInt(); int remainder, sum=0, product=1; for (int temp=number; temp!=0; temp = temp / 10)< remainder = temp % 10; sum = sum + remainder; product = product * remainder; >System.out.println("Sum of digits of Number '"+number+"'': "+sum); System.out.println("Product of digits of Number '"+number+"'': "+product); > >D:\Java_Programs>javac Digits.java D:\Java_Programs>java Digits Digits Sum and Product ----------------------- Enter Number: 153 Sum of digits of Number '153'': 9 Product of digits of Number '153'': 15Java Programming Computes Sum of Digits and Product of Digits using do while loop
import java.util.Scanner; public class Digits < public static void main(String args[]) < Scanner in = new Scanner(System.in); System.out.println("Digits Sum and Product"); System.out.println("-----------------------"); System.out.print("Enter Number: "); int number = in.nextInt(); int remainder, temp, sum=0, product=1; temp = number; do< remainder = temp % 10; sum = sum + remainder; product = product * remainder; temp = temp / 10; >while (temp!=0); System.out.println("Sum of digits of Number '"+number+"'': "+sum); System.out.println("Product of digits of Number '"+number+"'': "+product); > >D:\Java_Programs>javac Digits.java D:\Java_Programs>java Digits Digits Sum and Product ----------------------- Enter Number: 453 Sum of digits of Number '453'': 12 Product of digits of Number '453'': 60Sum of Digits of a Number in Java
One of the most fundamental programs is to add the digits of a number. The idea at play here aids in comprehending how loops work. The simplest way to find the sum of a number’s digits is to split the number into digits and add each one separately in integer form. In Java, there are various methods for calculating a number’s digit sum. These techniques will be covered in this article.
Steps to Find the Sum of Digits of a Number in Java
Enter any integer (or just take the number on its own). The sum of the number’s digits will then be determined by using the modulus and division procedures. Let’s examine the procedures.
- First, we assign the number as the initial value of the variable n. We start a variable called sumOfDigits with a value of 0.
- The last digit of the integer will be revealed when we use the modulo operator to calculate the remainder.
- The received digit (remainder) will then be continuously added to the sumOfDigits variable.
- In order to eliminate the last digit of the number, we must additionally divide the number n by 10.
- Up until the number n equals 0, repeat steps 2-4.
Approaches to find Sum of Digits of a Number in Java
Here, we will discuss three different approaches to calculate the sum of digits of a Number in Java.
Approach 1: Sum of Digits of a Number in Java By using for loop
The sumOfDigits is increased by the remaining n/10 after the for loop iterates until n!=0 is false. The for loop is broken and the sum is reported if n=0.
Code Implementation
import java.util.Scanner; class PrepBytes < public static void main(String arg[]) < long n, sumOfDigits; n = 23; for(sumOfDigits = 0 ; n!=0 ; n/=10) < sumOfDigits += n%10; // adding remainder(last digit) to the sum >System.out.println(sumOfDigits); // printing result > >Approach 2: Sum of Digits of a Number in Java By using Function
By enclosing our code in a function, we can also make it more organized and modular. We don’t need to repeatedly write its implementation because the function can be called from anywhere and will always return the sum of the digits.
Code Implementation
class PrepBytes < // sum function returns the sum of digits static long sum(long n) < long sumOfDigits = 0; // while the remaining number not becomes 0 while (n != 0) < sumOfDigits = sumOfDigits + n % 10; // adding last digit to sum n = n/10; // removing last digit >return sumOfDigits; // returning sum of digits > public static void main(String args[]) < long n; n = 23; System.out.println(sum(n)); // calling sum function for n >>Approach 3: Sum of Digits of a Number in Java By using Recursion
Recursion can also be used to calculate a number’s digit sum. Here, the presumption n==0 will be used. Until the initial condition is satisfied, the function will keep calling itself. Recursively calculating the remaining sum, the result from the remaining number is used each time the last digit is removed. The ternary operator is used in the programme below to write the aforementioned conditions. Run the code following the colon (:) in the ternary operator if the number is not zero; else, output 0. Recursively, the function sumOfDigits() is invoked.
Code Implementation
import java.util.*; class PrepBytes < static long sumOfDigits(long n) < // n == 0 is base condition return n == 0 ? 0 : n%10 + sumOfDigits(n/10) ; // calling function recursively >public static void main(String[] args) < long n; Scanner scn = new Scanner(System.in); n = 23; System.out.println(sumOfDigits(n)); // calling sumOfDigits fucntion >>
- A number’s digits are added by dividing it into its component parts and adding each one separately to produce the final result.
- We covered three approaches in Java to compute the sum of a number’s digits: for loop, function, and recursion.
FAQ related to Sum of Digits of a Number in Java
Q1: What happens if I enter a negative number?
Ans. The sum of digits calculation will still work for negative numbers. The sum will be calculated by considering the absolute values of the digits. For example, the sum of digits for -123 will be the same as the sum of digits for 123, which is 6.
Q2: Can I calculate the sum of digits for a decimal number?
Ans. No, the sum of digits calculation is typically used for integer numbers. If you need to calculate the sum of digits for a decimal number, you would need to convert it to an integer first by rounding or truncating the decimal part.
Q3: What is the "Sum of Digits of a Number" in Java?
Ans. The "Sum of Digits of a Number" refers to the calculation of the sum of all the individual digits of a given number.
Sum of Digits of a Number in Java
Adding the digits of a number is one of the most basic programs. The concept involved here helps in understanding how loops function. If we have a number and we need to find the sum of its digits, the simplest method is to divide it into digits and add each in integer form. There can be a few ways to find the sum of digits of a number in java. We'll go through those methods in this article.
Introduction
Whenever we need to find the solution to a problem, we first look at what's being provided to us. Isn't it? In this case, we will be given any number, and we have to calculate the sum of the digits (every integer that number is composed of).
Steps to Find the Sum of Digits of a Number in Java
Input any integer number (or the number can be taken by own). After that, we will apply the modulus and division operations to determine the sum of the digits of the number. Let's look at the steps.
- Firstly, we initialize the variable n n n with the number. We also initialize a variable sumOfDigits as 0 0 0 .
- Next, we will find the remainder using the modulo operator, which will give us the last digit of the number.
- After that, we will constantly add the obtained digit(remainder) to the sumOfDigits variable.
- At the same time, we also need to divide the number n n n by 1 0 10 1 0 , which removes the last digit of the number.
- Repeat steps 2 2 2 – 4 4 4 until the number n n n is equal to 0 0 0 .
By using for loop
The for loop iterates until n ! = 0 n!=0 n ! = 0 , then add the remainder of n / 1 0 n/10 n / 1 0 to the sumOfDigits until n ! = 0 n!=0 n ! = 0 is false . If n = 0 n=0 n = 0 , the for loop is interrupted, and the sum is printed.
By using Function
We can also make our code more modular and organized by putting it inside a function. The function can be called from anywhere, and it will return the sum of digits, and we need not write its implementation again and again.
By using Recursion
Sum of digits of a number can also be calculated with the help of recursion. Here we will use n = = 0 n == 0 n = = 0 as the base condition. The function will keep on calling itself till the base condition is met. Each time the last digit is chopped, the result from the remaining number is used again to calculate the remaining sum recursively. In the program given below, the above conditions are written with the help of a ternary operator. If the number is not zero, run the code after the colon (:) in the ternary operator; otherwise output 0 . The procedure sumOfDigits() is called recursively.
By using Command Line Arguments
Now, to calculate the sum of the digits of a number, we'll use command line arguments. The main method's " String args[] " will receive the command line parameters. We transform the value at index 0 to long using Long.parseLong(arg[0]) , where Long is the wrapper class.
Conclusion
- Adding the digits of a number means splitting the number into digits and adding each of them to obtain the result.
- To find the sum of digits of a number in java, we discussed four ways: using for loop, function, recursion, and command line arguments.
Sum of Digits of a Number in Java
In this post, we will write a program to print the sum of all the digits of a given number in Java. We will find the sum of digits of a number in Java using for loop. The while loop also can be used for this purpose. We can also develop a Java program to calculate the sum of digits without using any loop.
Program description:- Write a program to print the sum of all the digits of a given number in Java.
Example of the sum of digits of an integer number:- 54321 = 5+4+3+2+1 = 15
- Take a number
- Declare two variables:- lastDigit and sum
- Initialize the sum variable with 0
- Find the last digit of the number, lastDigit = number%10
- Add the value of lastDigit to the variable sum
- Remove the last digit of the number. number = number/10
- Repeat 4 to 6 steps until the number does not become 0
Using while loop
import java.util.Scanner; public class SumOfDigitsProgram < public static int digitSum(int number) < // declare variables int lastDigit = 0; int sum = 0; // loop to repeat the process while(number != 0) < // find last digit lastDigit = number % 10; // add last digit to sum sum = sum + lastDigit; // remove last digit number = number / 10; >// sum value is the sum of digits // of the given number return sum; > public static void main(String[] args) < // declare variables int number = 0; int sumOfDigits = 0; // create Scanner class object // for reading the values Scanner scan = new Scanner(System.in); // read input System.out.print("Enter an integer number::"); number = scan.nextInt(); // find sum of digits of number sumOfDigits = digitSum(number); // display result System.out.println("The sum of digits of" + " the number "+number+" = "+sumOfDigits); // close Scanner class object scan.close(); >>
The output for the different test-cases are:-
Enter an integer number:: 12345
The sum of digits of the number 12345 = 15
Enter an integer number:: 95423
The sum of digits of the number 95423 = 23
In this Java program, we have used a while loop to find the sum of digits of a given integer number. While loop is a pre-test loop where the expression is evaluated then only statements are executed. It uses a test expression to control the loop. Before every iteration of the loop, the test expression is evaluated.
We can find the last digit of the number and then add it to the sum variable using one line. It will reduce the number of line of the method which is using while loop.
public static int digitSum(int number) < // declare variables int sum = 0; // loop to repeat the process while(number != 0) < // find last digit and // add it to sum sum = sum + number % 10; // remove last digit number = number / 10; >// sum value is the sum of digits // of the given number return sum; >
Instead of using the while loop, we can also use for loop or do-while loop to find the sum of digits of a given integer number in java. The for loop is also a pre-test loop, where first of all initialization expression is evaluated then the condition is checked and if the condition is true then only the statements of the for loop are executed.
Sum of Digits of a Number in Java using for loop
public static int digitSum(int number) < // declare variables int sum; // loop to repeat the process for(sum = 0; number!=0; number/=10) // find last digit & add to sum sum = sum + number % 10; // sum value is the sum of digits // of the given number return sum; >
we can write more than one update expression inside for loop. So in the above program, we can reduce the number of lines in the for loop . Don’t forget to add semicolon (;) at the end of the for loop.
public static int digitSum(int number)< int sum; for(sum=0; number!=0; sum+=(number%10), number/=10); return sum; >
It can be also written as,
public static int digitSum(int number) < for(int sum=0; ; sum+=(number%10), number/=10) if(number==0) return sum; >
Sum of digits in Java without using the loop
We can also find the sum of digits in java without using any loop. For this purpose, we need to take the help of recursion technique. A method that calls itself is called the recursive method. Recursion is one of the ways to find a solution to the problem.
In the below program, we developed a recursive method digitSum(), this method finds the sum of the digits of a given number by using the recursion technique.
import java.util.Scanner; public class SumOfDigitsProgram < public static int digitSum(int n) < if(n==0) return 0; // base case else // general case return ( (n%10) + digitSum(n/10) ); >public static void main(String[] args) < // declare variables int number = 0; int sumOfDigits = 0; // create Scanner class object // for reading the values Scanner scan = new Scanner(System.in); // read input System.out.print("Enter integer number::"); number = scan.nextInt(); // find sum of digits of number sumOfDigits = digitSum(number); // display result System.out.println("The sum of digits of " + "the number "+number+" = "+sumOfDigits); // close Scanner class object scan.close(); >>
The if-else statement is used to write the condition and statement for the base and general case. We can also use the ternary operator.
public static int digitSum(int n) < return (n==0) ? 0 : ((n%10) + digitSum(n/10)); >
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!