write a programme to print sum of digits. Input = 2345, Output = 14.
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;
}
// Driver program
public static void main(String[] args)
{
int n = 687;
System.out.println(getSum(n));
}
}
// This code is contributed by mohakagr2010
Explanation:
Answer:
import java.util.Scanner;
class SumOfDigits{
public static void main (String args[]){
int sum = 0;
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number");
int n = sc.nextInt();
while(n>0){
sum += n%10;
n/=10;
}
System.out.println("The sum is = "+sum);
}
}