C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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

Liked this article? Do share with your friends :)

Are you a blogger? Join our Blogging forum.