Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

How to increment counter in TikZ using code below:

\newcounter{ga} %counter
\setcounter{ga}{1}
\begin{tikzpicture}
    \foreach \t in {1,...,10}{
      \pgfmathparse{Mod(\t,2) == 1 ? 1 : 0}
      \ifnum\pgfmathresult > 0
         \ga = \ga + 1
      \fi
\end{tikzpicture}

In line 4 I need something similar to \ga = \ga + 1.

share|improve this question
    
What is \ga? A TeX counter? A macro expanding to a number? –  Caramdir Jun 24 '12 at 22:35
2  
Then maybe you could post a complete MWE. –  Caramdir Jun 24 '12 at 22:38
2  
\stepcounter{ga}? –  Caramdir Jun 24 '12 at 22:50
1  
\stepcounter{ga} should do the trick. –  Werner Jun 24 '12 at 22:51
2  
You don't need that. As commented above, \begin{tikzpicture}\foreach \t in {1,...,10}{\pgfmathparse{Mod(\t,2) ==1?1:0}\ifnum\pgfmathresult>0\stepcounter{ga}\else\fi\node at (\t,0){\number\value{ga}};}\end{tikzpicture} is sufficient. –  percusse Jun 25 '12 at 1:22
show 5 more comments

2 Answers 2

\documentclass{minimal}
\usepackage{tikz}
\newcounter{ga}\setcounter{ga}{1}

\begin{document}

\foreach \t in {1,...,10}{\ifodd\t \stepcounter{ga}\fi}
\thega
\end{document} 
share|improve this answer
add comment

It's not really a question about TikZ but about the package pgffor and pgfmath. With Tikz I prefer to use the TeX's macros here \newcount, it's more natural if you use \ifdim.

update

I forgot that I'm the author of Integer arithmetics functions in pgfmath, It's possible to use isodd. But \ifodd from Herbert's answer is the correct way with \newcount.

It's perhaps important to develop the difference between the answers. I feel reticent about mixing TeX's macros and LaTeX's macros.

1) It's important to notice that LaTeX’s counters are set globally.

2) The need to use the lower-level TeX system is not obvious but the spirit of TikZ and here for the macro \foreach, it's to work if it's possible locally. The difference is that TeX sets count registers locally. So to do a global assignment you have to do it deliberately like with \global\advance\ga by1 in my code.

A good document (tex-counts-and-latex-counters) is here from Joseph Wright

\documentclass[11pt]{article}
\usepackage{tikz}    % or \usepackage{pgffor,pgfmath}  pgf 2.1cvs

\begin{document}
\newcount\ga
\ga=1 %

\foreach \t in {1,...,10}{%
%\pgfmathparse{Mod(\t,2)==1?1:0}
  \pgfmathparse{isodd(\t)}  
\ifnum\pgfmathresult>0 \global\advance\ga by1 \fi
}

\the\ga
\end{document} 

Result : 6

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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