I believe that \foreach is not the best tool for this job.
But you might do it: the printing should be inside the loop, at the last step and you want int.
\documentclass{article}
\usepackage{pgffor}
\newcommand\routine[1]{%
\pgfmathsetmacro\temp{0}%
\foreach[parse=true][remember=\temp] \i in {1,...,#1} {%
\pgfmathsetmacro\temp{int(\temp+\i)}%
\ifnum#1=\i\relax\temp\fi
}%
}
\begin{document}
\routine{5}
\end{document}
Here's an expandable implementation.
\documentclass{article}
\makeatletter
\newcommand{\triangular}[1]{%
@triangular{0}{0}{#1}%
}
\newcommand{@triangular}[3]{%
% #1 is the current step
% #2 is the accumulated total
% #3 is the step we want to get at
\ifnum#1=#3
\expandafter@firstoftwo
\else
\expandafter@secondoftwo
\fi
{\the\numexpr#2+#1}%
{\expanded{\noexpand@triangular{\the\numexpr#1+1}{\the\numexpr#2+#1}{#3}}}%
}
\makeatother
\begin{document}
\triangular{0}\par
\triangular{1}\par
\triangular{2}\par
\triangular{3}\par
\triangular{4}\par
\triangular{5}\par
\triangular{6}
\edef\test{\triangular{10}}
\texttt{\meaning\test}
\end{document}

Without \expanded a slightly more complicated version is needed
\newcommand{\@triangular}[3]{%
% #1 is the current step
% #2 is the accumulated total
% #3 is the step we want to get at
\ifnum#1=#3
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{\the\numexpr#2+#1}%
{\expandafter\@triangular
\expandafter{\the\numexpr#1+1\expandafter}%
\expandafter{\the\numexpr#2+#1}{#3}%
}
}
Finally, the expl3 code:
\documentclass{article}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\triangular}{m}
{
\acter_triangular:nnn { 0 } { 0 } { #1 }
}
\cs_new:Nn \acter_triangular:nnn
{
% #1 is the current step
% #2 is the accumulated total
% #3 is the step we want to get at
\int_compare:nTF { #1 = #3 }
{% reached
\int_eval:n { #2 + #1 }
}
{% restart
\acter_triangular:een { \int_eval:n { #1 + 1 } } { \int_eval:n { #2 + #1 } } { #3 }
}
}
\cs_generate_variant:Nn \acter_triangular:nnn { ee }
\ExplSyntaxOff
\begin{document}
\triangular{0}\par
\triangular{1}\par
\triangular{2}\par
\triangular{3}\par
\triangular{4}\par
\triangular{5}\par
\triangular{6}
\edef\test{\triangular{10}}
\texttt{\meaning\test}
\end{document}
\foreachloop are defined locally and are forgotten as soon as the loop ends. – egreg Oct 22 '22 at 07:16\pgfmathparseinside\pgfmathsetmacro. That is not correct. Just do\pgfmathsetmacro\temp{\temp+\i}(and then what ever else you need to do with\temp). In this case, I'd rather use the function(#1)*(#1+1)/2. – Qrrbrbirlbel Nov 21 '22 at 13:56