Write a Java program to calculate the sum of the digits of a given number
This program calculates the sum of the digits of a given number (userNo). Here’s a detailed breakdown of the logic:
What Does the Program Do?
Given an integer, the program extracts its digits, adds them together, and outputs the result.
For example:
- Input: 321
- Calculation: 3+2+1=6
- Output: Sum of digits: 6
class Main {
public static void main(String[] args) {
int userNo = 321; // Input number
int sum = 0; // Variable to hold the sum of digits
// Calculate the sum of the digits
while (userNo != 0) {
sum += userNo % 10; // Add last digit to sum
userNo /= 10; // Remove last digit from the number
}
// Print the sum of digits
System.out.print("Sum of digits: " + sum);
}
}
Sum of digits: 6
Input Initialization:
userNo = 321: The number for which we calculate the sum of digits.
sum = 0: A variable to accumulate the sum of the digits.
Digit Extraction and Summation:
A while loop runs until userNo becomes 0.
Logic inside the loop:
userNo % 10: Extracts the last digit of userNo.
Example: For 321, 321 % 10 = 1 (last digit).
sum += userNo % 10: Adds the extracted digit to sum.
After the first iteration, sum = 0 + 1 = 1.
userNo /= 10: Removes the last digit from userNo by performing integer division by 10.
After the first iteration, userNo = 321 / 10 = 32.
Iteration Breakdown for userNo = 321:
Iteration 1:
Extract last digit: 1
Add to sum: sum = 0 + 1 = 1
Update number: userNo = 321 / 10 = 32
Iteration 2:
Extract last digit: 2
Add to sum: sum = 1 + 2 = 3
Update number: userNo = 32 / 10 = 3
Iteration 3:
Extract last digit: 3
Add to sum: sum = 3 + 3 = 6
Update number: userNo = 3 / 10 = 0
Loop ends when userNo becomes 0.
Output the Result:
After the loop, sum contains the total of all digits in the input number.
The program prints the result using System.out.print().