no % 10
.
no = no/10
).
public class SumOfDigits
{
public static void main(String[] args)
{
int no = 624;
int sum = 0;
while (no != 0)
{
int digit = no % 10; // Extract the last digit
sum = sum + digit; // Add the digit to the sum
no = no / 10; // Remove the last digit
}
System.out.println("The sum of the digits is: " + sum);
}
}
The sum of the digits is: 12
import java.util.Scanner;
public class SumOfDigits
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int no = scanner.nextInt();
int sum = 0;
while (no != 0)
{
int digit = no % 10; // Extract the last digit
sum = sum + digit; // Add the digit to the sum
no = no / 10; // Remove the last digit
}
System.out.println("The sum of the digits is: " + sum);
scanner.close();
}
}
Enter a number: 1427 The sum of the digits is: 14
Scanner
and store it in an integer variable no
.
sum
to 0 to keep track of the sum of the digits.
while
loop that runs until no
becomes 0:
no % 10
. sum (sum += digit)
. no
using no = no/10
. System.out.println()
.
scanner.close()
to avoid resource leaks.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.