5

I use pgffor package and I have

\foreach \n in {1,...,10}{**something I want**}

How can I print n*(n+1) for each n?

When I write just \n*(\n+1) instead of **something I want**,

1(1+1)2(2+1)3(3+1)...

appears.

6
\documentclass{article}
\usepackage{pgffor}
\begin{document}
\foreach \x in {1,...,10}{%
  \texttt{Something you want : \the\numexpr\x*(\x+1)/2\relax}\par}
\end{document}

enter image description here

9

Please post compilable or at least copy/pastable code so that we can see what you want to do. Until then

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\foreach \x[evaluate=\x as \evalx using int(\x*(\x+1)/2)] in {1,...,10}{
\texttt{Something you want : \evalx}

}
\end{document}

enter image description here

5

Since PGF and PGFPlots are getting married to Lua as well, here is another example in LuaLaTeX.

\documentclass{article}
\begin{document}
\directlua{
for n = 1,10 do
 tex.sprint(n*(n+1)/2 ..', ')
 end
}
\end{document}
4

A more flexible solution with fp just for fun. My example below uses an extreme case which is f(x)=sin(x*π/10) instead of your simple case which is f(x)=x*(x+1)/2.

\documentclass[preview,border=12pt,12pt,varwidth]{standalone}
\usepackage{pgffor}
\usepackage[nomessages]{fp}

%\def\f[#1]{#1*(#1+1)/2}% f:x --> x*(x+1)/2
\def\f[#1]{sin(#1*pi/10)}% XTreme case just for generalization

\begin{document}
\foreach \i in {0,...,10}{%
    \FPset\x{\i}%
    \FPeval\y{\f[x]}%
    \FPeval\y{round(y:3)}% you can use 0 to get an integer
    $f(\i) = \y$ \par
}
\end{document}

enter image description here

Edit

For your case.

\documentclass[preview,border=12pt,12pt,varwidth]{standalone}
\usepackage{pgffor}
\usepackage[nomessages]{fp}

\def\f[#1]{#1*(#1+1)/2}% f:x --> x*(x+1)/2
%\def\f[#1]{sin(#1*pi/10)}% 

\begin{document}
\foreach \i in {1,...,10}{%
    \FPset\x{\i}%
    \FPeval\y{\f[x]}%
    \FPeval\y{round(y:0)}%
    $f(\i) = \y$ \par
}
\end{document}

enter image description here

1

For comparison, here is an example using the TeX primitive integer arithmetic operators and the plain TeX \loop macro.

\documentclass{article}
\newcount\n\newcount\tn
\def\triangles#1{1%
\n=1
\loop\ifnum\n<#1
\advance \n  by 1 \tn=\n
\advance \tn by 1 
\multiply\tn by \n
\divide  \tn by 2
, \number\tn \repeat}
\begin{document}
\triangles{15}.
\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.