sum of all digits of a number in java code example
Example 1: Java program to find the sum of all the digits in the inputted number
long number, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any DIGIT number: ");
number = sc.nextLong();
sc.close();
for (sum = 0; number != 0; number /= 10) {
sum += number % 10;
}
System.out.println("ForLoop Sum of ALL digits: " + sum);
Example 2: to get sum of even digits java
public static int getEvenDigitSum(int number){
if(number<0){
return -1;
}
int finalNumber=0;
while(number>0){
if((number%10)%2==0){
finalNumber+=number%10;
}
number=number/10;
}
return finalNumber;
}
Example 3: sum of numbers in java
public class SumNatural {
public static void main(String[] args) {
int num = 100, sum = 0;
for(int i = 1; i <= num; ++i)
{
sum += i;
}
System.out.println("Sum = " + sum);
}
}