×

Java Programs

Java Practice

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 */
		while(number>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);
	}
}

Output

Enter any number
12345
Sum of digits are : 15

Core Java Example Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.