Ad

Wednesday, February 10, 2016

Codecademy Learn Java tutorial walkthrough 9 Math:modulo %

Modulo has always been a difficult concept for beginners. Codecademy tutorials always cover Modulo operator (the percentage sign %) because it is extremely useful in math, programming and engineering in general. This is a step by step, detailed programming language agnostic guide to how to use and understand the modulo operator. 

First of all don't think too much about the name of the percentage symbol. Let's first understand the concept of modulo. 

It's very useful when determining whether number x is divisible by number y. Say 10 is divisible by 1, 2, 5, and 10. The result is always a whole number: 10, 5, 2, 1 respectively. When x is divisible by y, the result of x modulo y is always zero. 10 % 1 = 0, 10 % 2 = 0. When x is divisible by y, the result is always zero, because there's no remainder. 10 % 3 = 1. Because 3x3=9 plus the remainder 1 equals to 10. And in this case, x moduloes y is not zero, and hence x is not divisible by y. 

And now another commonly used case for the modulo operator: determining whether a number is even or odd. It's useful say Udacity has an online class full of students, and now wants to divide the students methodically into different groups. The sorting method will be different depends on whether the number of students is even or odd. We can calculate that using z % 2. Z is the number of students. example 10%2 =0 makes 10 even. 9%2 = 1, so 9 is not even.


In this exercise, I set int myNumber equal to 11%3, and the remainder will be 2 because 3 x3 is 9, 9 plus 2 is 11, see the illustrated traditional calculation 




5 comments:

  1. This was worth reading article, java is no doubt the most powerful programming languages yet more demanding as well. J2EE Training in Chennai | JAVA Training in Chennai

    ReplyDelete

React UI, UI UX, Reactstrap React Bootstrap

React UI MATERIAL  Install yarn add @material-ui/icons Reactstrap FORMS. Controlled Forms. Uncontrolled Forms.  Columns, grid