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.

I need to write a recursive algorithm, using the algorithms package.

I thought of writing something like this:

\begin{algorithmic}
\IF {$x=1}
    \RETURN 1
\ELSE
    \RETURN recurse$(x-1)$
\ENDIF
\end{algorithmic}

The problem here is that it's not obvious that the function "recurse" will call this very function (that is unnamed to start with) again. Is there a better way of doing it, besides stating in the text that "recurse" - well, recurses?

share|improve this question
    
In your original question it said "algorithmic package". Did you mean algorithmicx or algorithms (or maybe even algorithm2e)? –  Hendrik Vogt Feb 22 '11 at 8:08
    
Sorry for my detailed response - the packages I import are \usepackage{algorithm} and \usepackage{algorithmic} . When I first wrote the algorithms, I did not know which package to used, and a Google search suggested that these were the packages usually used - hence I formatted my algorithms with these in mind. I can re-write them for a new package, of course, if it offers a solution to my problem. –  Sewi Mar 2 '11 at 11:48
    
That should read "delayed" instead of "detailed". I will use the algorithmicx package as Konrad suggested - being able to encapsulate the algorithm in a procedure should be the least ambiguous way of describing recursion. –  Sewi Mar 2 '11 at 11:55

1 Answer 1

up vote 5 down vote accepted

There doesn’t seem to be a way of defining procedures in algorithms but you can use an algorithm environment with an appropriate \caption that names your algorithm.

Personally, though, I would switch to the superior algorithmicx package that defines a \Procedure macro:

\begin{algorithm}
\Procedure{recurse}{$x$}
  \If{$x=1$}
    \State\Return{$1$}
  \Else
    \State\Return{\Call{recurse}{$x-1$}}
  \EndIf
\EndProcedure
\end{algorithm}
share|improve this answer
    
It may be that the OP is already using algorithmicx; see my comment to the question. (Doesn't matter too much for your answer :-)) –  Hendrik Vogt Feb 22 '11 at 8:09
    
A procedure macro was exactly what I was hoping for. The syntax of the algorithmicx package seems quite similar to the algorithmic package, so there should be little overhead rewriting the algorithms. Thank you, Konrad. –  Sewi Mar 2 '11 at 11:52

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.