latex If statements


Example

In latex we can use built-in commands to execute code whether the conditions are true or not.

Comparing two integers: \ifnum\value{num}>n {A} \else {B}\fi

This code executes A if num>n else B. We can substitute > with < and =.

If a number is odd: \ifodd\value{num} {A}\else {B}\fi

If num is odd then it executes A else B.

If with condition: \ifthenelse{condition}{A}{B}

We have to load ifthen package to use this command. If condition are true then it executes A else B.

It is possible to create complex condition with \( \), \AND, \OR, \NOT.

For example: \ifthenelse{\(\NOT 4<2 \OR 4>11\)\AND\isodd{4}}{A}{B}

This piece of code writes down "B" on the page. \NOT 4<2 is true and 4>11 is false. If we connect a false and a true statement with "OR" then the result is true. So \(\NOT 4<2 \OR 4>11\) is true. \isodd{4} is false because 4 is even. A false and a true statement connected with "AND" is false, so the output is B.

An example code:

\documentclass{article}
\usepackage{ifthen}
\begin{document}
    \newcounter{num}
    \setcounter{num}{10}

    If num$>$100 then the next sentence will be "Num is large." else "Num is small."

    Num is \ifnum \value{num}>100 {large} \else {small}.

    If num is odd then the next sentence will begin with "Odd" if not then with "Even"

    \ifodd \value{num} {Odd} \else {Even} numbers are cool.

    If (num$>$3 and (1$<$0 or num$=$10)) is true then the next sentence will be "True." else "False."

    \ifthenelse{\value{num}>3\AND\(1<0 \OR \value{num}=10\)}{True.}{False.}


\end{document}

result