2

Suppose that one has the following pseudo code, written in LaTeX using the package algorithms:

\documentclass[]{article}

\usepackage{algorithm}% http://ctan.org/pkg/algorithms
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx

\begin{document}
\begin{algorithm}[t]
\caption{Euclid example}\label{euclid}

\begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
    \State $r\gets a\bmod b$ and foobar\label{foobar}
    \For{$i \gets 1$ to $n$}
    \While{$r\not=0$}\Comment{We have the answer if r is 0}
    \State $a\gets b$
    \State $b\gets r$
    \State $r\gets a\bmod b$
    \EndWhile\label{euclidendwhile}
    \EndFor
    \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}

Written like that, it does work. However, when I try changing the like \For{$i \gets 1$ to $n$} to \For{$i \gets 1$ \To $n$} or \For{$i \gets 1$ \TO $n$} it then does not compile, with the error "Undefined control sequence". Still, according to the package's documentation, it should work (see page 5 of the official documentation at http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/algorithms/algorithms.pdf).

What am I doing wrong? How else could I get the to connector in a for-loop, so that the to appears in bold and in the same font as loop and do?

1

algpseudocode is part of algorithmicx and it does not provide \To or \TO. It's algorithmic (from the algorithms bundle) that provides \To.

Define your own \To:

enter image description here

\documentclass{article}

\usepackage{algorithm,algpseudocode}

\algnewcommand{\To}{{\normalfont\bfseries to }}

\begin{document}

\begin{algorithm}[t]
  \caption{Euclid example}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d.\ of $a$ and $b$}
      \State $r\gets a \bmod b$ and foobar
      \For{$i \gets 1$ \To $n$}
        \While{$r \neq 0$}\Comment{We have the answer if $r$ is $0$}
          \State $a \gets b$
          \State $b \gets r$
          \State $r \gets a \bmod b$
        \EndWhile
      \EndFor
      \State \textbf{return} $b$\Comment{The g.c.d.\ is $b$}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}

\end{document}

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.