Search code examples
delphidelphi-7

Delphi 7 - perform operation if (var) = 1,3,5,7 etc


my Delphi 7 is very basic so I apologise in advance if this seems like a dumb question. I want my code to do something if a number is either 1 or 3 or 5 etc etc. or else do something else if it is 2 or 4 or 6 etc etc. Any advice would be greatly appreciated. Thanks

Tony


Solution

  • You're probably looking for the odd() function.

    It returns true for 1,3,5,7, and it returns false for 2,4,6.

    Example

    var
      x: Integer;
    ....
    x := ...;
    if odd(x) then
      writeln('x is odd')
    else
      writeln('x is even')
    

    More generally if you wanted to test for divisibility by a number other than two you would use the mod operator. The returns the remainder of an integer division. So

    if x mod 3 = 0 then
      writeln('x is divisible by 3')
    else
      writeln('x is not divisible by 3')