[Tex/LaTex] How to increment variable by using same variable

counterspgfmath

How can I increment variable from the same variable?

\pgfmathsetmacro\S{5};
\pgfmathsetmacro\S{\S + 1};%   not working

How can I work around this? I need counters which I use as line coordinates increment in certain conditions.

Update

\pgfmathsetmacro\cA{0}; 
\newcounter{cB}
\foreach \x in {1,...,10}
{ 
    \pgfmathtruncatemacro\cA{\cA+1)};
    \pgfmathaddtocounter{cB}{1};            
    \node at (\x,1) { \cA };
    \node at (\x,0) { \the\numexpr\value{cB} };         
}

printed out this

1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1

I need

1 2 3 4 ...

Yes, I could do this in this simple example by just using \x variable but in my real diagram I need to increment them irregularly. So I need variable which can be incremented inside the loop without resets. Or, am I missing something and it should work?

Best Answer

To be used in a \foreach loop, there are better options:

\documentclass[tikz,border=2pt]{standalone}
\begin{document}

\begin{tikzpicture}
\foreach \i [count=\S from 5] in {1,...,5}
    \node [draw, xshift=\i cm] {\S};
\end{tikzpicture}

\end{document}

enter image description here

where the syntax count=\S from 5 is used here to set \S to 5 and advance it by 1 in each iteration. Another syntax may be evaluate=\i as \S using \i+4, which will achieve the same result.

Update

The increment can be changed within the loop based on a condition like this:

\newcounter{cA} 
\setcounter{cA}{0}
\newcounter{cB}
\setcounter{cB}{0}

\begin{tikzpicture}
\foreach \x in {1,...,10}{ 
    \addtocounter{cA}{1}
    \ifnum\x<6\addtocounter{cB}{1}\else\addtocounter{cB}{2}\fi            
    \node at (\x,1) { \thecA };
    \node at (\x,0) { \thecB };          
}
\end{tikzpicture}

enter image description here

Related Question