Java Program to Find Sum of Digits of a Number
Finding the sum of digits of a number is a common beginner-level programming problem in Java. It helps learners understand loops and number manipulation.
In this tutorial, we will create a Java program that calculates the sum of all digits in a given number using a loop.
By the end of this guide, you will understand how digit extraction works in Java using arithmetic operators.
Concept Overview
To find the sum of digits, we repeatedly extract the last digit using the modulus operator (%) and add it to a sum variable.
We then remove the last digit using division (/) and repeat the process until the number becomes zero.
Program
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
while (num != 0) {
int digit = num % 10;
sum += digit;
num = num / 10;
}
System.out.println("Sum of digits: " + sum);
}
}
Output
Enter a number: 1234
Sum of digits: 10
Detailed Explanation
The program starts by taking input from the user using the Scanner class.
A variable sum is initialized to 0 to store the total.
Inside the loop, the last digit is extracted using num % 10.
This digit is added to the sum variable.
The number is reduced using num = num / 10.
The loop continues until the number becomes 0.
Example Walkthrough
Let us consider the input 1234.
Step-by-step: 1 + 2 + 3 + 4 = 10.
Applications
Digit sum logic is used in checksum calculations, data validation, and cryptography.
Advantages of This Approach
This program helps beginners understand loops and arithmetic operations.
It demonstrates how numbers can be processed digit by digit.
Limitations
The program does not handle negative numbers or invalid inputs.
Improvements You Can Make
You can extend this program to handle negative numbers.
You can also use recursion instead of loops.
You can integrate it into a larger calculator program.
This Java program builds strong foundational skills in loops and number manipulation.
Codecrown