0

I'm trying to draw an array but also have the indexes beneath them. Right now, all I have is this

enter image description here

Here is my code:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}

\begin{figure}
\centering
  \begin{tikzpicture}
    \coordinate (s) at (0,0);
    \foreach \num in {3, 1, 4, 1, 5}{
      \node[minimum size=6mm, draw, rectangle] at (s) {\num};
      \coordinate (s) at ($(s) + (1,0)$);
    }
  \end{tikzpicture}
\label{fig:testArray}
\end{figure}
\end{document}

Any help would be greatly appreciated!

4

This might give the desired results:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcounter{index}

\begin{document}

\begin{figure}
\centering
  \begin{tikzpicture}
    \setcounter{index}{0}
    \coordinate (s) at (0,0);
    \foreach \num in {3, 1, 4, 1, 5}{
      \node[minimum size=6mm, draw, rectangle] at (s) {\num};
      \node at ($(s)-(0,0.5)$) {\theindex};
      \stepcounter{index}
      \coordinate (s) at ($(s) + (1,0)$);
    }
  \end{tikzpicture}
  \label{fig:testArray}
\end{figure}
\begin{figure}
\centering
  \begin{tikzpicture}
    \setcounter{index}{0}
    \coordinate (s) at (0,0);
    \foreach \num in {2, 7, 1, 8, 2}{
      \node[minimum size=6mm, draw, rectangle] at (s) {\num};
      \node at ($(s)-(0,0.5)$) {\theindex};
      \stepcounter{index}
      \coordinate (s) at ($(s) + (1,0)$);
    }
  \end{tikzpicture}
  \label{fig:testArray2}
\end{figure}
\end{document}

enter image description here EDIT: I restructured the code a little to be less prone to errors.

| improve this answer | |
  • This helps. However, when I used this same code for another figure, I got an error. Can you help with that too please? – Jose Acuna Aug 13 '17 at 17:43
  • 1
    @JoseAcuna I can't if you don't show the code, obviously. And the error message would come in handy, too. You might open another question or edit yours (without removing the original question). If the issue is caused by my code, editing would be fine. If it is by your code, a new question would be better, I guess. – Skillmon likes topanswers.xyz Aug 13 '17 at 17:47
  • @JoseAcuna if I had to guess, it's because you reused the line \newcounter{index}. The counter is defined globally, so you should only issue the \newcounter command once. Instead use \setcounter{index}{0}. – Skillmon likes topanswers.xyz Aug 13 '17 at 17:56

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.