Sum of Digits of a Number in Java using For loop
ADVERTISEMENTS
Sum of digits of a number in java using for loop. In this article, you will learn how to find the sum of digits of a number in java using for loop.
Sum of Digits of a Number
An integer number of 4 digits is 1459 ==> 1 + 4 + 5 + 9 ==> 19
Source Code
// Sum of Digits of a Number in Java using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the integer number::\n");
int x = in.nextInt(),
sum = 0,
m;
System.out.print ("The sum of " + x + " digits is = ");
while (x > 0) {
m = x%10;
sum = sum+m;
x = x/10;
}
System.out.println (sum + "\n");
}
}
Output
Enter the integer number::
1459
The sum of 1459 digits is = 19