Program to sum the digits of a number (Java)

So today we are going to write program that accepts a number from the user and print the sum of its digits. So this is a very simple program and it does not require much logic to write this program.
So lets get started...


Q. Write a program that accepts an integer from the user and print the sum of its digits.
For Example: Input: 123 , and Output: 1+2+3=6

Solution:
123456789101112131415161718 import java.util.*;
 class SumOfDigits
 {
     public static void main(String[] args)
     {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a number: ");
         int n = sc.nextInt();
         int reminder,sum = 0;
         for(int i = n;i > 0;i=i/10)
         {
             reminder = i%10;
             sum = sum+reminder;
         }
         System.out.println("Sum of digits of " + n + " = " + sum);
     }
 }

Code Written in BlueJ
Output:
1234Enter a number: 
123
Sum of digits of 123 = 6


Output in BlueJ

Variable description used in program:
int n - It is used to accept a number from user.
int reminder - It is used to take last digit from the given number i.e., Its reminder when divided by 10.
int sum - It is used the add the digits if the given number.
Explanation:
In this program we first we accepted a number i.e., "int n", from the user through Scanner class and then we created a variable reminder and sum. And then we used for() loop to add the digits of the number i.e., "int n". In for() loop "int reminder" is used to take the last digit of the number when divide by 10 and "int sum" is used to add the reminder i.e., digits of the given number. And after the for() loop we printed the sum of the digits. This is how this program works.

So that is it to print the Sum of Digits program. Hope you find it useful and if you have any query do comment in the comment box and I will try to solve your query. Will see you on next program.

Thank You.
Program to sum the digits of a number (Java) Program to sum the digits of a number (Java) Reviewed by Get2Know on October 03, 2020 Rating: 5

No comments:

Powered by Blogger.