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);
}
}
The article on "Sum of the Digits in Java" provides a clear and concise explanation of this fundamental programming concept. It's a valuable resource for Java learners looking to understand digit manipulation.
ReplyDeleteSchools near Vanasthalipuram
our recent blog post on calculating the sum of digits in Java is a gem for both beginners and seasoned developers alike! The clarity and simplicity with which you break down this seemingly magical process make it incredibly accessible.
ReplyDelete