Sum of Digits
This program calculates the sum of digits of a number using while loop.
Problem Statement
Write a Java program that calculates the sum of digits of 1234 using while loop.
Source Code
| 1 | public class SumDigits { |
| 2 | public static void main(String[] args) { |
| 3 | int num = 1234, sum = 0; |
| 4 | while(num > 0) { |
| 5 | sum += num % 10; |
| 6 | num /= 10; |
| 7 | } |
| 8 | System.out.println("Sum of digits = " + sum + " - Eduinq"); |
| 9 | } |
| 10 | } |
Program Output
Sum of digits = 10 - Eduinq
Explanation
The program extracts digits using num % 10 and adds them to sum. Then it removes the last digit using num /= 10. The loop continues until num becomes 0. This demonstrates how while loops can process digits sequentially. Shows how while loop can calculate sum of digits.