Home » Java solved programs » Core java programs

Java program to add digits of a number

In this java program, we are going to learn how to add digits of a given number? Here, we are reading an integer number and find addition of all digits.
Submitted by Preeti Jain, on March 11, 2018

Given an integer number and we have to find addition of all digits using java.

Add all digits of a number in java

import java.util.Scanner;

class AddDigitsOfANumberClass{
	public static void main(String[] args){
		/* sum variable store sum of digits */

		/* last_digit variable contain last digit 
		of a number until loop termination */
		int sum = 0,last_digit;

		Scanner sc = new Scanner(System.in);

		/* Display message for number input */
		System.out.println("Enter any number");

		/* Number input from user */
		int number = sc.nextInt();

		/* loop continue number remain 0 */

			/* get last digit of a number */
			last_digit = number%10;

			/* add last digit to the sum */
			sum = sum+last_digit;

			/* truncate last digit from number */
			number = number/10;

		/* After loop completion results will display */
		System.out.println("Sum of digits are : " + sum);


Enter any number
Sum of digits are : 15

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions

© https://www.includehelp.com (2015-2018), Some rights reserved.

close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.