modulus % operator code example
Example 1: modulo operator
Example: 5 % 2 = 1
Think about it like this:
Of 5 items, remove as many sets of 2 as you can. Whatever item(s) remains
is the answer, aka the remainder.
Visual example of 5 % 2:
Start with 5 items:
item1, item2, item3, item4, item5
Remove 2:
item3, item4, item5
Remove another 2:
item5
No more sets of 2 can be removed and there is 1 item remaining. So the answer
would be 1
More general:
n % m
Of n items, choose as many sets of m as you can. Whatever item(s) remains
is the answer, aka the remainder.
Example 2: what is modulus operator
// given a list of widgets, files, people, etc.
longList = 10000;
feedbackInterval = 100; // to be used as the modulus
// loop over the list to process each item
for( i=1; i <= longList; i++ ) {
// perform some operation
// mod operation gives feedback once every hundred loops
if( i % feedbackInterval == 0 ) {
percentCompleted = ( i / longList ) * 100;
writeOutput( "#percentCompleted# percent complete. " );
}
}