Write
a program that reads an integer between 0 and
10000 and adds all the digits in the integer. For example, if an integer
is 932, the
sum
of all its digits is 14.
Description:
Use
the % operator to extract digits,
and use the / operator to remove the
extracted
digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
Solution
import java.util.*;
public class Message {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num,sum=0;
System.out.println("Enter the mass in
pound");
num=in.nextInt();
sum+=num%10;
num/=10;
sum+=num%10;
num/=10;
sum+=num%10;
num/=10;
sum+=num%10;
num/=10;
sum+=num%10;
num/=10;
System.out.println("The sum of all the
element is ="+sum);
}
}
Output:
No comments:
Post a Comment