Java Program to Find Sum of Digits of a Number

Here is a 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;

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) {
            digSum += num % 10;
            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;

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));
    }

    public static int getDigitSum(int num) {
        int digSum = 0;
        while (num != 0) {
            digSum += num % 10;
            num = num / 10;
        }
        return digSum;
    }
}
Output
Enter an Integer
100
Sum of Digits = 1
Enter an Integer
1011
Sum of Digits = 3

Recommended Posts
Java Program to Count Number of Digits in a Number
Java Program To Reverse Digits of a Number using While Loop
Java Program to Find Factorial of a Number Using Recursion
Java Program to Find LCM and GCD of Two Numbers
Java Program to Calculate Arithmetic Mean of N Numbers
Java Program to Print Pascal Triangle
Java Program to Find Sum of Elements of an Array
Java Program to Calculate Compound Interest
Java Program to Check Whether a Number is Armstrong Number or Not
Java Program to Print Fibonacci Series with and without using Recursion
Java Program to Calculate Average and Percentage Marks
All Java Programs