In this tutorial you will learn about the Java Program to Calculate Sum of Digits and its application with practical example.
Java Program to Calculate Sum of Digits
In this tutorial, we will learn to create a Java program that will Print the Sum of digits in a given Number using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- While loop in Java programming.
- Conditional Statements in Java programming.
- Arithmetic operations in Java Programming.
Program to Print Sum of digits in a given Number
In Java programming, we will make a program in today’s tutorial. We will take integer input from the user and find the Sum of digits in a given number with the help of a program. At last, we will print the sum of all the digits in that number.
With the help of this program, we can Print the Sum of digits in a given number.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables required for the program. 2. Taking the input number from the user for the program. 3. Calculating the total number of digits in the numbers. 4. Calculating the sum of all the numbers in the given number. 5. Printing the result numbers. 6. End Program |
Program to Print Sum of digits in a given number:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.Scanner; public class SOD//Main class of the prorgam. { //Body of the main function of the program. public static void main(String args[]) { //Declaring the required variables for the program. int no, digit, sum = 0; //no = it will hold the integer for the input //digit = it will hold the digits of the number //sum = it will hold the sum of the digits //Taking the input number from the user. Scanner sc = new Scanner(System.in); System.out.print("Enter the number: "); no = sc.nextInt(); //Adding the digits of the number while(number > 0) { //finds the last digit of the given number digit = no % 10; //adds last digit to the variable sum sum = sum + digit; //removes the last digit from the number no = no / 10; } //prints the result sum to the user System.out.println("Sum of Digits: "+sum); } } |
Output:-
In the above program, we have first initialized the required variable.
- no = it will hold the integer for the input
- digit = it will hold the digits of the number
- sum = it will hold the sum of the digits
Input number from the user.
Program Logic Code.
Printing output for sum the digits.