Very often while programming, we come across problems where we need to find the sum of the digits of an integer. We generally use the while loop to solve this problem.
We keep on finding the remainder of the number after dividing it by 10 so that we can extract each digit. We also keep reducing the number by dividing it by 10 until the number becomes zero.
Below is a program written in Java that demonstrates this:
import java.io.*;
class SumOfDigits{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num, rem, sum=0;
System.out.print("Enter the integer:");
num=Integer.parseInt(br.readLine());
while(num!=0){
rem=num%10;
sum+=rem;
num/=10;
}
System.out.println("Sum of digits = "+sum);
}
}