# If-else-fi within foreach with recursion

Given a list of numbers of size n, n-1 combinations are formed. The numbers of each combination are multiplied and all the products are added. This is taken from question 711870. Recursion works on paper. The question is where is the error in the following development. Thank you for your time.

\documentclass[10pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[left=2.5cm, right=1.5cm, top=2.5cm, bottom=1.5cm]{geometry}
\usepackage[spanish]{babel}
\usepackage{mathtools, amssymb, amsthm}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\foreach \i [count=\Mc] in {3,5,7}{ %--
\ifnum \Mc<2
\let\M=1
\let\N=\i
\node at (0,\Mc){M=\M, \quad N=\N, posición=\Mc, Valor=\i};
\else
\pgfmathparse{\i*\M+\N}
\pgfmathsetmacro{\M}{\pgfmathresult}
\pgfmathsetmacro{\N}{\i*\N}
\node at (0,\Mc){M=\M, \quad N=\N, posición=\Mc, Valor=\i};
\fi
};
\end{tikzpicture}
%----------------------------------------------------
\end{document}

• Welcome to TeX.SE! Please translate your title of your question into english language. Mar 4 at 19:57
• you don't define \M or \N in the iterations after the first (and \foreach runs each iteration in a group. so you get an undefined command error on \N when it is used Mar 4 at 20:04
• If you change the \lets in the first branch of the \ifnum to \xdef\M{1}\xdef\N{\i}, you can get it to compile. However, it is not clear whether you need the updated values of \M and \N to carry through to each successive loop iteration. If you do, then you can add \global\let\M\M\global\let\N\N to the end of the 2nd branch of the \ifnum. Mar 4 at 20:22
• What is "question 711870"?
– Mico
Mar 4 at 20:34

Any cycle in \foreach is performed in a group, so you lose the value of \M and \N.

But you can remember them, see TikZ manual (page 1005) about /pgf/foreach/remember, so there's no need to do global assignments (at least in this case), with the risk of clobbering existing commands.

\documentclass[10pt,a4paper]{article}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

\begin{tikzpicture}
\foreach \i [
count=\Mc,
remember=\M as \lastM (initially 1),
remember=\N as \lastN (initially \i),
] in {3,5,7}{
\ifnum \Mc<2
\pgfmathsetmacro{\M}{\lastM}
\pgfmathsetmacro{\N}{\lastN}
\else
\pgfmathsetmacro{\M}{\i*\lastM+\lastN}
\pgfmathsetmacro{\N}{\i*\lastN}
\fi
\node at (0,\Mc){M=\M, \quad N=\N, posición=\Mc, Valor=\i};
}
\end{tikzpicture}

\end{document}


Note tha you don't want a semicolon after the closing brace of \foreach, because \foreach is not a statement.