+ 1

Can someone explain why the modulo is used to calculate sum of integers?

import java.util.Scanner; public class Main { public static void main(String[] Strings) { Scanner input = new Scanner(System.in); System.out.print("Input an integer between 0 and 1000: "); int num = input.nextInt(); int firstDigit = num % 10; int remainingNumber = num / 10; int SecondDigit = remainingNumber % 10; remainingNumber = remainingNumber / 10; int thirdDigit = remainingNumber % 10; remainingNumber = remainingNumber / 10; int fourthDigit = remainingNumber % 10; int sum = thirdDigit + SecondDigit + firstDigit + fourthDigit; System.out.println("The sum of all digits in " + num + " is " + sum); } }

26th Sep 2019, 9:56 PM
Andy M
Andy M - avatar
3 Answers
+ 1
Here is a code with explanation how to get the sum of digits for any numbers: https://code.sololearn.com/cpRTncew8x5O/?ref=app
26th Sep 2019, 11:30 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Modulo with 10 always gives you the last digit of number. By dividing number with 10 you are getting rid of the last digit. This code just repeats these two to get all digits of number and then adds them.
26th Sep 2019, 10:02 PM
Irma MasleĆĄa
Irma MasleĆĄa - avatar
0
So if the numbers were from 0 to 999 would you still be able to program using the modulo or would there be another way to add the integers?
26th Sep 2019, 10:46 PM
Andy M
Andy M - avatar