Write a program in java to input a number and calculate the sum of its digits
Answers
Answer:
// Java program to compute
// sum of digits in number.
import java.io.*;
class GFG {
/* Function to get sum of digits */
static int getSum(int n)
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
Explanation:
Please follow me and I will follow you back.
Please mark my answer as the brainliest.
Answer:
import java.util.*:
public class Sum
{
public static void main(String args[])
{
Scanner in= new Scanner (System.in);
int a,n,m,l,s=0;
System.out.println("Enter the number");
a= in.nextInt();
n=Math.count(a);
for(m=1;m<=n;m++)
{
l=(a%10);
s=s+l;
System.out.println("The sum is =" +s);
}
}
}
Explanation:
As it is a terminating program so we should use loop here. Such that "for loop".
We cannot decide the number of digits of the number so we have to count the number of digits and terminate the loop that much of times.
To get the digits particularly we should devide the number by 10 and each time accept the remainder.