latex Counters, if statements and loops with latex Operations with counters


Example

This example shows how to use mathematical operations with counters. It may be useful for loops in latex.

Addition: \addtocounter{num}{n}

this command adds n to num, where num is a counter and n is a positive integer.

Subtraction: \addtocounter{num}{-n}

this command subtracts n from num, where num is a counter and n is a positive integer.

Multiplication: \multiply\value{num} by n

this command multiply num by n, where num is a counter and n is an integer.

Division \divide\value{num} by n

this command divides num by n and gets the integer part of the quotient (num is a counter and n is an integer)

\documentclass{article}
    \begin{document}
    \newcounter{num}
    \setcounter{num}{3}
    \addtocounter{num}{10}
    \thenum\\%prints 13
    \addtocounter{num}{-3}
    \thenum\\%prints 10
    \stepcounter{num}
    \thenum\\%prints 11
    \multiply\value{num} by \value{num}
    \thenum\\%prints 121
    \multiply\value{num} by 2
    \thenum\\%prints 242
    \divide\value{num} by 60
    \thenum%prints 4
\end{document}

\newcommand{num} declares counter. \setcounter{num}{3} sets num value to 3.

\addtocounter{num}{10} adds 10 to num.

\addtocounter{num}{-3} subtract 3 from num.

\stepcounter{num} adds 1 to num

\multiply\value{num} by \value{num} squares num.

\multiply\value{num} by 2 doubles num.

\divide\value{num} by 60 divides num by 60 and gets the integer part.

The result of the code: 13\\10\\11\\121\\242\\4

(\\ symbolizes new line)

intcalc package adds some other integer operations e.g. mod, pow, sng, abs, inv ...

intcalc_package.pdf