Skip Navigation Links.
Using the Mod operator.
Language(s):Delphi
Category(s):Modulo

The Mod operator is a useful but little used function. Here is an example of how and why you might use it.

{
  This sample code is presented as is.
  Although every reasonable effort has been
  made to insure the soundness of the example
  below, Idioma Software inc. makes no warranty
  of any kind with regard to this program sample
  either implicitly or explicitly.

  This program example may be freely distributed for the
  use of writing computer programs only. Any other use of
  this material requires written permission from Idioma Software inc.

  (c) 1997 Idioma Software inc. All rights reserved.
 }


{
   This example shows how to use the Mod operator.
 }
Procedure ModEx;
{Author Jon Vote 11/97}
var i,j : integer;
    year : word;
    isLeapYear : boolean;

begin
{
 The modulo (Mod) operator returns the remainder when divided by.
 This can be used to repeat a range of numbers over and over or to map
 a large number within a range of smaller numbers:
}
for i := 1 to 1000 do
 j := ( i mod 60); {j will go from 0 to 59, 0 to 59 - etc.}

{
 Add a constant to range between something other than 0
}
for i := 1 to 1000 do
 j := (i mod 12) + 1; {j will go from 1 to 12, 1 to 12 - etc.}

{
 You can map numbers to a range - for example
 convert a number greater than 360 to an angle in degrees
}
for i := 360 to 10000 do
 j := i mod 360; {j will always be a valid angle}

{
 Perhaps the most common use is determining leap year.
 A leap year is any year divisible by 4 except for years divisible by
 100 and not by 400.
}

year := 2024; {put whatever value you like here}

{If year mod 4 is 0, the year is divisible by 4}
if year mod 4 = 0 then {might be a leap year}
  {if year mod 100 is 0, the year is divisible by 100}
  if year mod 100 = 0 then
    {if year mod 400 is 0, the year is divisible by 400}
    if year mod 400 = 0 then
      isLeapYear := true {This is a millennium leap year}
    else {Wasn't divisible by 400 here - not a leap year}
      isLeapYear := false
  else {was divisible by 4 but not 100. It's as leap year as apple pie.}
    isLeapYear := true
else {year mod 4 was not 0 - Can't be a leap year}
  isLeapYear := false;

if isLeapYear then
  ShowMessage(IntToStr(year) + ' it''s a leap year mattie.') 
else
  ShowMessage(IntToStr(year) + ' ain''t no leap year me bucko.');

end;

This article has been viewed 6851 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.