Written by Sai Sameera Thota on January 16, 2013 in Java > Programming

# Java Program to find Sum of Individual Digits

This program illustrates how to perform the sum of individual digits in Java, The program takes a number as input and displays the sum of the individual digits in the number as output.

For example,

input : 427

output: 4 + 2 + 7 = 13

The variables `sum`

and `num`

are initialized to zero.

The modulo operator(%) gives the remainder of the given digit. In the given example, 427 % 10 = 7. The remainder 7 is added to the sum and the value is stored in the variable sum. In the next step the number is divided by 10 i.e, 427/10 = 42. The loop iterates till the value of `n`

becomes zero.

//Sum of individual digits of a number
import java.io.*;
class sum_digits
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter a number : ");
int n = Integer.parseInt(br.readLine());
int num = 0,sum = 0;
while(n!=0)
{
num = n%10;
sum = sum + num;
n = n/10;
}
System.out.print("\nSum of individual digits : "+sum);
}
}

Output:

*Related*

Tagged as:
Java Programs

Sai Sameera has written **36** articles for us.

{ 0 comments… add one now }