tech Java Program Sum Of digits Of A Number | Programs
Latest :

Java Program Sum Of digits Of A Number | Programs

Java program to calculate the sum of digits of a number. Here we will discuss the various methods to calculate the sum of the digits of any given number with the help of Java Programs. The compiler has been added so that you can execute the program yourself, alongside suitable examples and sample outputs. The methods as mentioned above are:

  • Using For Loop.
  • Using Static Method.
  • Using Command Line Arguments.
  • Using Recursion.

Using For Loop

1) Here we are using the for loop to calculate the sum of digits of a number.

2) Read the entered long value using scanner class object sc.nextLong().

3) The for loop iterates up to n!=0, here sum=0, and n=n/10,add the remainder of n/10 to the sum until n!=0 is false. If n=0 then for loop will be terminated, and prints the sum value.

Output:

Using Static Method

1) Static method sum(long num), will calculate the sum of digits of a number.

2) Read entered value. Call the static method sum(n) in the main method then the static method will be executed. This method adds the remainder to sum and n=n/10, these 2 steps will repeat until num!=0. If num=0 then it returns the sum value.

Output:

Using Command Line Arguments

1) The command line arguments will be passed to “String args[]” of the main method.

2) Using Long.parseLong(arg[0]), we are converting the value at index 0 as long, here Long is the wrapper class.

3) Repeat these two steps sum=sum+n%10; n/=10; until n!=0, if n=0 then while terminated and print the sum value.

Output:

Using Recursion

1) We are calling the method using the class SumOfDigits to object “s” as s.sum(n) then sum() starts the execution.

2) Sum method calls itself as sum(num), it repeats until num!=0. If num=0 then it returns the sum value.

Output:

More Java Programs:

tech
x

Check Also

Merge Sort Java – Program 2 Ways | Sortings

Merge Sort Java –  Java program to implement merge sort using array & Buffered reader. ...