Java Program to Find Sum of Digits of a Number

  • Java Program to find the sum of digits of a number using while loop and using a function.

Given a number N, we have to add all digits of a N and print the sum on screen.
For Example,
Sum of digits of 2534 = 2 + 5 + 3 + 4 = 14

To find sum of digits of a number, we will extract digits one by one from N using '/' and '%' operator and add it to a sum variable. N%10 will give the least significant digit of N. To remove least significant digit from N we will divide N by 10.

For Example,
Last digit of a number : 5342 % 10 = 2
Removing last digit from a number : 5342/10 = 534

Java program to add digits of a number using while loop

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to check a number is perfect number or not
 */
public class DigitSum {
    public static void main(String[] args) {
        int num, i, digSum = 0;
        Scanner scanner;
        scanner = new Scanner(System.in);

        System.out.println("Enter an Integer");
        num = scanner.nextInt();

        while (num != 0) {
            /*
             * get the least significant digit(last digit) of num and add it to
             * digSum
             */
            digSum += num % 10;
            /*
             * remove least significant digit(last digit) form num
             */
            num = num / 10;
        }

        System.out.format("Sum of Digits = %d", digSum);
    }
}
Output
Enter an Integer
786
Sum of Digits = 21
Enter an Integer
1010
Sum of Digits = 2

Java program to find sum of digits of a number using function

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to check a number is perfect number or not using function
 */
public class DigitSumFunction {
    public static void main(String[] args) {
        int num;
        Scanner scanner;
        scanner = new Scanner(System.in);

        System.out.println("Enter an Integer");
        num = scanner.nextInt();

        System.out.format("Sum of Digits = %d", getDigitSum(num));
    }

    /**
     * This function returns the sum of digits of num
     */
    public static int getDigitSum(int num) {
        int digSum = 0;
        while (num != 0) {
            /*
             * get the least significant digit(last digit) of num and add it to
             * digSum
             */
            digSum += num % 10;
            /*
             * remove least significant digit(last digit) form num
             */
            num = num / 10;
        }
        return digSum;
    }
}
Output
Enter an Integer
100
Sum of Digits = 1
Enter an Integer
1011
Sum of Digits = 3