Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Sum of digits of a number using Java

Sum of digits of a number using java :

In this article we will find the sum of digits of an integer. For this purpose we will use a loop and a variable to sum the digits of the number entered by the user. Let us consider some examples for better understanding :

Input : 27

Output : Sum of Digits = 9

Input : 12345

Output : Sum of Digits = 15

So, now we create a java program to calculate the sum of digits of a given number.

Sum of digits of a number using java

Working :

Step 1 : Ask the user to enter an integer and store that integer value in a variable, number.

Step 2 : Declare a variable sod and initialize it with 0.

Step 3 : Use a while loop to pick the digits of the integer and count the number of digits one by one.

Step 4 : Use a statement to pick the last digit of the integer..

Step 5 : Perform addition and store it in variable sod

Step 6 : Restore the value of number by removing last digit in every iteration of the loop.

Step 7 : Repeat the Steps from 3 to 6 till the value of number becomes 0.

Step 8 : Display the value of sod.

Code in Java :

//Java program to calculate sum of digits of a number
import java.util.Scanner;
public class sum_of_digits
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
//declare a variable to store sum of digits
int sod = 0;
while(number != 0)
{
int pick_last = number % 10;
sod = sod + pick_last;
number = number / 10;
}
//display sum of digits
System.out.print("Sum of Digits = "+sod);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a number : 123

Sum of Digits = 6


Enter a number : 4563

Sum of Digits = 18