JRJC - How To Use Modulo

Modulo is nothing more than "remainder after division."

So 20 modulo 5 is 0 because 20 divided by 5 is 4 with no remainder.

In C, C++ and Java, modulo is represented as the percent sign. So

    int a = 20 % 5 ;

sets a to be zero.

Modulo has a variety of uses. If you want to know if a number is an even "hundred", like 300, 400, 500 or 256700, you can test for it like this:


    if ( ( a % 100 ) == 0 )
    {
        System.out.println( a + "exactly!");
    }

Another cool thing to do with modulo is when you are doing big processes, you can let the user know that your program isn't stuck:

    TextFileIn f = new TextFileIn("bigfile.txt");
    int numLines = 0 ;
    boolean done = false ;
    while( ! done )
    {
        String s = f.readLine();
        if ( s == null )
        {
            done = true ;
        }
        else
        {
            // processing the big file goes here
            numLines++;
            if ( ( numLines % 1000 ) == 0 )
            {
                System.out.print(".");
            }
        }
    }

This program fragment will read in a file, process it, and write a dot to the screen for every 1000 lines processed.






For more information, please visit my java site.

And for a change of pace, you can visit my permaculture site.






© 2000 paul wheaton