Tuesday, December 13, 2011

Java program to calculate sum of digits of a given number

The following is the java program to calculate sum of digits in a given number. It is easy to calculate sum of digits. first we will read the input number by using buffered reader and we will store that number in a variable. Later we will extract each digit by using  %10. Every time it returns last digit of a number. This process is done until all digits are covered.

/* Simple Java Program To Find the Sum of digits of number */
import java.io.*;
class calcsum
{
public static void main(String args[]) throws Exception
{
int sum, i,a,d;
System.out.println("Enter A Number ");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(k.readLine());
sum = 0;
while(a!=0)
{
d = a%10;
a = a/10;
sum=sum + d;
}
System.out.println("Sum of Digits :"+sum);
}
}


output:



1 comment:

  1. Very Useful. For more examples visit http://answersz.com

    ReplyDelete