# The Magical Mod Function

by Steven J. Engelbrecht

Remember when you were in elementary school and had to do long division on paper? Before we learned about decimals and fractions we used to show the remainder as part of our answer. For instance, 22 / 7 = 3 R1. Remember?

Without even knowing it, we were mimicking a relatively obscure function in ASP called "mod", short for "modular division" or "modulo" in Latin. The "modulus", or remainder, is what is left over when we divide one number by another.

`Syntax: number1 mod number2`

For example, 22 mod 7 will yield an answer of 1. Likewise, 1 mod 7 will yield an answer of 1, as the answer is 0 with a remainder of 1.

Let's see it in action. Here's a simple script that will show the modulus of 1 through 10 divided by 5:

 ``` <% For i = 1 to 10 Response.write(i & " mod 5 = " & i mod 5 & "
") Next %> ```

This little script will give the following output:

1 mod 5 = 1
2 mod 5 = 2
3 mod 5 = 3
4 mod 5 = 4
5 mod 5 = 0
6 mod 5 = 1
7 mod 5 = 2
8 mod 5 = 3
9 mod 5 = 4
10 mod 5 = 0

Get it?

Many advanced encryption techniques, including the world-standard RSA Encryption Algorithm, use the mod function as part of their internal functioning. But surely there must be some useful applications of this little guy for the rest of us, right?

Well of course there are! Let's start with a fact that you may not have considered...

## Any Positive Integer Mod 2 is Binary

Makes sense, right? Any positive integer when divided by 2 will have a remainder of either 0 or 1. Here's another little script to show off mod's mystical powers:

 ``` <% For i = 1 to 10 If i mod 2 = 1 Then Response.write(i & " is odd.
") Else Response.write(i & " is even.
") End If Next %> ```

Could this be useful to you? Maybe not like this, but here's the same idea in function form.

 ``` <% Function isOdd(iInput) IsOdd = CBool( iInput Mod 2 ) End Function %> ```

Not bad right? Now, we'll look at a truly useful application of the mod function: creating well-formed tables with a variable number of items to be displayed.

Recently I created a dynamic web-based photo album, and one of the views I wanted to add was a thumbnail display of all my images. Obviously I couldn't just loop through and display the images without a table, and it didn't make sense to show one thumbnail per row, so I was faced with an interesting challenge: how can I make sure the table is complete, i.e. has the same number of cells in every row, if I don't know how many items I'll be looping through?

Let me make sure you understand the problem before I explain the solution. Say we want a table with 3 cells in each row, and there are, for example, 9 items to be displayed. No problem, right? Three rows of three and we're done. But now suppose there are 10 items. Now, to keep the table well-formed (so it won't create any problems when viewed in unforgiving browsers), we have to create three rows of three, then an additional row with one cell containing the 10th item, then two empty cells and a close row tag. That's one problem. Now suppose we want to give the user the option of showing 3, 4, or 5 items per row. Obviously this wouldn't be fun to do by creating a bunch of nested if..thens or select cases. How can we manage this programatically?

## Mod to the Rescue

To start, let's define a simple point that will permeate this example. If we want x items per row, and we have y items to be displayed, then if item_number mod x = 1 it will be the first item in the row, and if item_number mod x = 0 it will be the last item in the row (with item_number ranging from 1 to y). If item_number mod x is greater than 1, then it is an internal cell in the table and does not need an open row or close row tag next to it.

For example, here's how we could add 9 items to a table with 3 elements in each row:

 ``` <% iCellsPerRow = 3 iItems = 9 ' Create the table strOutput = "" ' Loop through all items For i = 1 to iItems ' Check to see if this is the start of a new row If i mod iCellsPerRow = 1 Then strOutput = strOutput & "
" & i & "
" ' Add a cell for this item strOutput = strOutput & "" ' Check to see if this is the end of a row If i mod iCellsPerRow = 0 Then strOutput = strOutput & "" Next ' Close the table strOutput = strOutput & "" ' Write the HTML output Response.write(strOutput) %> ```

Now if you're super observant, you may have noticed that this code won't work with a number of items that isn't evenly divisible by the number of cells per row. That's because we need one more clever piece of code to find out how many empty cells we have to add so that the last row matches up with the others. So now, after we've added all the elements to the table, we check first to see if we're at the end of a row, in which case we don't have to proceed, otherwise we create the rest of the row using empty cells.

The complete algorithm is as follows:

 ``` <% iCellsPerRow = 3 iItems = 9 ' Create the table strOutput = "" ' Loop through all items For i = 1 to iItems ' Check to see if this is the start of a new row If i mod iCellsPerRow = 1 Then strOutput = strOutput & "
" & i & "

" ' Add a cell for this item strOutput = strOutput & "" ' Check to see if this is the end of a row If i mod iCellsPerRow = 0 Then strOutput = strOutput & "" Next ' If we're not at the end of a row, ' fill the rest of the row with empty cells. If iItems mod iCellsPerRow > 0 Then ' Loop through to complete table For j = 1 to iCellsPerRow - (iItems mod iCellsPerRow) ' Add an empty cell strOutput = strOutput & "" ' Add a close row tag if this is the last cell. If j = iCellsPerRow - (iItems mod iCellsPerRow) Then _ strOutput = strOutput & "" Next End if ' Close the table strOutput = strOutput & "" ' Write the HTML output Response.write(strOutput) %> ```

## Conclusion

Unless you're in the cryptography business, mod is generally overlooked as a truly "useful" function in web programming. But, if you create shopping carts, online stores, photo albums, calendars, etc., anything that might need the flexibility of tables with variable numbers of items and/or items per row, it's a great tool to have under your belt.

The example I've created reads in two parameters: the number of cells per row, and the total number of items. It then runs some simple error checking on these inputted numbers, casts them as integers, then creates a table using the above described algorithm. For those of you that are interested, I also added the nice touch of calculating the width of the cells if you want them to be evenly spaced.

#### From ASP101

Articles originally posted on ASP101.com

• #### Neutral website provides A couple of new things regarding nike shoes that no company is discussing.

Posted by moisseenfogma on 05/16/2013 01:32pm

Y [url=http://www.nikekutuja.biz/]nike running[/url] rjMsh AfiIqs JitMhv Mxi [url=http://www.nikekutuja.biz/air-jordanç©ºæ°ã¨ã«ãã³-c-1.html]air jordan[/url] QkqTucYqt Bk [url=http://www.nikekutuja.biz/air-maxã¨ã¢ããã¯ã¹-c-2.html]air max 95[/url] oDsfPrbBdb XjlGxyAks [url=http://www.nikekutuja.biz/nike-air-force-1ãã¤ã­ã¨ã¢ãã©ã¼ã¹-c-4.html]air force[/url] Fbf YlvKgq Bc [url=http://www.nikekutuja.com/]nike running[/url] gLon WfiPfy SzrUfi HrtC [url=http://www.nikekutuja.com/air-jordanç©ºæ°ã¨ã«ãã³-c-1.html]nike air jordan[/url] jqIgbPtr LylGobRozO [url=http://www.nikekutuja.com/nike-dunkãã¤ã­ãã³ã¯-c-4.html]nike dunk low[/url] jv YnvQjkUa [url=http://www.nikekutuja.com/air-maxã¨ã¢ããã¯ã¹-c-2.html]nike air max[/url] cQew MakKpa Cp [url=http://www.nikekutujp.com/]nike ã¹ãã¼ã«ã¼[/url] eXsx ZoyMva WlyKxg DlfQ [url=http://www.nikekutujp.com/nike-dunkãã¤ã­ãã³ã¯-c-4.html]nike store[/url] txPiqPre K [url=http://www.nikekutujp.com/nike-air-force-1ãã¤ã­ã¨ã¢ãã©ã¼ã¹-c-3.html]air force[/url] eySvoKjfMpw [url=http://www.nikekutujp.com/air-jordanç©ºæ°ã¨ã«ãã³-c-1.html]nike jordan[/url] SqdKtnHheZer TztFfl

• #### Nike Draught Max+instagram, desire you take the color to step on your feet!

Posted by madytreathy on 04/22/2013 05:31am

• #### New one

Posted by snareenactina on 01/03/2013 08:48pm

fccmrviolet You have to ask yourself why retirees move to states run by Republicans rather than Democrats. Got any pithy answers to that one? As this graph shows, the UK plunged into recession in 2008, and emerged in the last three months of 2009. It then suffered a sharp contraction in the final quarter of 2010, shrinking by 0.5% - which was blamed on the particularly bad weather last winter. More and more companies are seeking job candidates with some kind of international experience. impenetrable New Economy today released the latest edition of the Manchester Monitor, which provides an analytical snapshot of the economic wellbeing of Greater Manchester. karimov Ake, Anne. Austria. San Diego: Lucent Books, 2001. political For anon35534 how can you cite a picture of this, for it is only a type of economy? Maybe a picture as to where they use this type of economy would help you. ~Just another wiseGEEK here. Have a nice day! volley Enfin, les chiffres que vous citez doivent ÄÅtre pris en considÄÂ©ration avec une autre information : le Royaume-Uni est lÃ¢â¬â¢un des rares pays ÄÂ  avoir ouvert ses frontiÄÂ¨res aussi massivement aux travailleurs de lÃ¢â¬â¢Est, ce qui nÃ¢â¬â¢est pas le cas de la France. turock Link to this comment: jobbankusda I do believe that the poor and middle class have a much better Ã¢â¬Åquality of lifeÃ¢â¬Å¥ in Europe than the US but Europeans should remember that it is only through the grace of the US that it is allowed to do so. My mother is French and my father is Italian. I am a first generation Ã¢â¬ÅAmericanÃ¢â¬Å¥. I was raised with the European mentality because of my parents but I understand the Ã¢â¬ÅAmericanÃ¢â¬Å¥ way of life because I was born here. I am afraid to say that it is becoming more difficult to Ã¢â¬Åfulfil the American dreamÃ¢â¬Å¥ in this day and age. Outsourcing, illegal immigration, and higher taxes are preventing anybody from the bottom of the economic chain to elevate themselves. kristof A new way for lawyers to create another ambulance-chasing industry? How's that for unintended consequences?

• You must have javascript enabled in order to post comments.

## Top White Papers and Webcasts

• Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

• U.S. companies are desperately trying to recruit and hire skilled software engineers and developers, but there is simply not enough quality talent to go around. Tiempo Development is a nearshore software development company. Our headquarters are in AZ, but we are a pioneer and leader in outsourcing to Mexico, based on our three software development centers there. We have a proven process and we are experts at providing our customers with powerful solutions. We transform ideas into reality.

## Most Popular Programming Stories

• There have been no articles posted today.