# How to display an array with the indexes beneath them

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

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!

## 1 Answer

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}


EDIT: I restructured the code a little to be less prone to errors.

• 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
• @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