Java: All Hail Modulus Agustus! The modulus operator is used all the time. Realize that if you “mod” any number by a number “n”, you’ll get back a number between 0 and n-1. For example, “modding” any number by 20 will always give you a number between 0-19. Your job is to design implement (source code) a program to sum the total of all digits in an input integer number between 0 and 1000, inclusive. Notice that you need to extract individual digits from the input number using the remainder (modulus) and division mathematical operators. For example, if the input number is 123, the sum of its digits is 6. Document your code and properly label the input prompts and the outputs as shown below.
Sample run 1: Entered number: 123 Sum of digits: 6
Sample run 2: Entered number: 588 Sum of digits: 21
Sample run 3: Entered number: 100 Sum of digits: 1
import java.util.Scanner;
public class SumDigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number: ");
int num = sc.nextInt();
int r = 0, sum = 0;
int dup = num;
while(dup>0){
r = dup %10; // IT GETS END DIGIT OF NUMBER FOR EX 123 IT RETURN
3
sum = sum + r;
dup /= 10; // IT RETURN NUMBER/10 FOR EX 123/10 = 12
}
System.out.println("Entered Number: "+num+" Sum of digits:
"+sum);
}
}
/* OUTPUT */
Get Answers For Free
Most questions answered within 1 hours.