๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

WAP to calculate the sum of digits in a number in Java  


Logical Steps:
  • Take one number.
  • Initialize a sum variable to 0 to store the sum of the digits.
  • Use a loop:
    • In each iteration, extract the last digit using no % 10.
    • Add the extracted digit to the sum.
    • Remove the last digit by dividing the number by 10 ( no = no/10).
    • Repeat until the number becomes 0.
  • Print the sum as the result.
Programs:
  • Below is the simple program:
    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);
        }
    }
    Output:
    The sum of the digits is: 12
  • Below is the program by taking user input:
    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();
        }
    }
    Output:
    Enter a number: 1427
    The sum of the digits is: 14
Program Explanation
  • Take input from the user using Scanner and store it in an integer variable no.
  • Initialize a variable sum to 0 to keep track of the sum of the digits.
  • Use a while loop that runs until no becomes 0:
    • Extract the last digit using no % 10.
      Example: For 12345, the last digit is 5.
    • Add the digit to sum (sum += digit).
      Example: sum = 0 + 5 = 5.
    • Remove the last digit from no using no = no/10.
      Example: 12345 becomes 1234.
  • Repeat the process until all digits are processed.
  • Print the result, which is the sum of the digits, using System.out.println().
  • Close the scanner with scanner.close() to avoid resource leaks.