Beta Coder

Learn code like Beta Coder.

Breaking

Friday, September 18, 2020

Java Program to Evaluate the sum of all digits of a given number

EVALUATE THE SUM OF ALL DIGITS OF A GIVEN NUMBER

JAVA EVALUATE THE SUM OF ALL DIGITS OF A GIVEN NUMBER
In this program we learn how to evaluate the sum of all digits of a given number by provided user using Java.
Java program to evaluate the sum of all digits of a given number
// EVALUATE THE SUM OF ALL DIGITS OF A GIVEN NUMBER
import java.util.*;
class SumOfDigits
{
	int n;
	public
		SumOfDigits()
{ Scanner in = new Scanner(System.in); System.out.print("\n Enter a number : "); n = in.nextInt(); } int cal() { int r, s = 0; do { r = n % 10; s = s + r; n = n / 10; }while(n != 0); return(s); } void display(int p) { System.out.println("\n The sum of digits = "+p); } public static void main(String arg[]) { SumOfDigits a = new SumOfDigits();
int p; p = a.cal(); a.display(p); } };
OUTPUT:
   Enter a number : 12542
   The sum of digits = 14

No comments:

Post a Comment