reset password
Author Message
wcwir
Posts: 75
Posted 17:45 Sep 22, 2019 |

If you are struggling with the % operator, you are not alone. It is like using a new tool -- seems impossible until it clicks. Remember when you tried using chopsticks for the first time? Or riding a bicycle? % is not inherently harder than *, so if you mastered multiplication, you will master remainder. You just need to use it over and over.

How can we use it to figure out future day of week in LAB 5?

Actually, you can get around without using it:

For example, today is Sunday, and we label Sundays with “0”, Monday with “1”, and so on with “6” for Saturday. What day will it be in 10,000 days?

Well, we know Sunday occurs every 7 days. So since today is Sunday, there will be another Sunday in 7 days, and then in 14 days, and then in 21 days, and then in 28 days – any number of days from today that is divisible by 7 will be Sunday.

But 10,000 is not divisible by 7. In fact, 10,000 / 7 is 1,428.571428571429 if you do it on a calculator, and if you do it in Java it is1,428 because the fractional part gets lopped off in integer division. So in (1428 * 7) days, which is 9,996 days, it will be Sunday again. So in 9,997 days it will be Monday, and in 9,998 days it will be Tuesday, and in 9,999 days will be Wednesday, and in 10,000 days it will be Thursday.

And if you really hate the % operator, then you could figure out if a number is divisible by 7 like so:

(num == (num / 7) * 7)

This will evaluate to true if the number is divisible by 7, and false otherwise. Try it! (In our case, if num is 10000, then we will get 10000 == 9996, which is false)

And you can also figure out how many days after Sunday the future day will be without using the % operator, like so:

daysPastSunday = num - ((num / 7) * 7);

In our case, this will evaluate to 4, because 10000 - 9996 is 4. And four days past Sunday it will be Thursday.

But all that could be simplified with % operator!

If today is Sunday, then in 10,000 days it will be day corresponding to:

10000 % 7;

Which is 4! Because that's what % does: it tells us what remains when we divide one number by another.

OK, but your program should work on every day of the week, and not just Sundays... Well: try to understand how it works when you start with Sunday first. We'll talk it more during lecture on Monday.

Last edited by wcwir at 17:49 Sep 22, 2019.