Integer Arithmetic – Intro to Java Programming


You just worked with Sarah on a few questions on arithmetic operations. But I want to talk about the somewhat trickier aspect on how to do division with integers. Let’s say I have a piggy bank full of pennies, and then I want to know how many dollars do I have. In Java, I can computer that with a division operation, and there’s a bit of a catch. When both operands on the left and on the right hand side of the division slash our integers, then the quotient is formed, and the remainder is discarded. Mathematically, 435 divided by 100 is of course 4.35. And then, the 0.35 is gone. The leftover is 4 as an integer. And that number here is now saved as the dollars. That’s just what we want, right? 435 pennies is $4. What if we also want the pennies, for that we have a different operator called the modulus operator, and we often just pronounce it as mod. By the operand on the right, let’s try that out with 435. 435 divided by 100 is 4. So, there’s 4 times 100 going in here. When we take those off, we’re left with a remainder of 35. That was no longer divisble by 100. That’s what the remainder operator yields. You can see that by making an integer division by 100, and then also a reminder operation with 100 then we get the dollars and the cents value. Now, it’s time for you try this tell me what is. Pennies integer divided by ten and pennies mod 10.

Leave a Reply

Your email address will not be published. Required fields are marked *