Basic calculations in PGF/TikZ for loop

Tikz allows to perform calculations on a variable using the syntax [evaluate=\x as... using...] see pages 983 and 984 of the 3.1.3 manual.

\documentclass{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{amsmath}
\usepackage{pgffor}
\usepackage{tikz}
\usepackage{calc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usetikzlibrary{calc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

\foreach \x [evaluate=\x as \xx using int(\x-1)]in {1,...,5} { $\xx$ }

\end{document}

enter image description here


A proof of concept with expl3:

\documentclass{article}
\usepackage{xparse,xfp}

\ExplSyntaxOn

\NewDocumentCommand{\intloop}{O{1}mm}
 {% #1 = start, default 1; #2 = end; #3 = template
  \cs_gset_protected:Nn \__tjt_intloop_function:n { #3 }
  \tjt_intloop:nn { #1 } { #2 }
 }

\cs_new:Nn \tjt_intloop:nn
 {
  \int_step_function:nnN { #1 } { #2 } \__tjt_intloop_function:n
 }

\ExplSyntaxOff

\begin{document}

\intloop{5}{\inteval{#1-1}}

\bigskip

$\begin{array}{c|c}
n & f(n) \\
\hline
\intloop{5}{#1 & \fpeval{2*(#1)^2-4} \\}
\end{array}$

\end{document}

enter image description here


Here are two alternatives to using evaluate. You can use \the\numexpr or just loop over 0,...,4. Only pgffor is needed for that.

\documentclass{article}
\usepackage{amsmath}
\usepackage{pgffor}
\begin{document}

\foreach \x in {1,...,5} { $(\the\numexpr\x-1)$ }

\foreach \x in {0,...,4} { $(\x)$ }
\end{document}