[Tex/LaTex] Subroutine in algorithm2e

algorithm2ealgorithms

I am looking for a tiny example of writing in algorithm2e an algorithm using a subroutine.

The algorithm is called algo, and it recursively calls a subroutine called proc.
It should be something like below in one environment:

Algorithm 1 algo()
1 xxx
2 xxx
3 proc()
4 return
Procedure proc()
1 xxx
2 return

I do not want to write these two things using two different algorithm environments.
Can anyone show me an example?

Best Answer

Here is one version.

Sample output

\documentclass{article}
\usepackage{algorithm2e}

\begin{document}
\thispagestyle{empty}

\begin{algorithm}[htp]
  \SetAlgoLined\DontPrintSemicolon
  \SetKwFunction{algo}{algo}\SetKwFunction{proc}{proc}
  \SetKwProg{myalg}{Algorithm}{}{}
  \myalg{\algo{}}{
  \nl xxx\;
  \nl xxx\;
  \nl \proc{}\;
  \nl \KwRet\;}{}
  \setcounter{AlgoLine}{0}
  \SetKwProg{myproc}{Procedure}{}{}
  \myproc{\proc{}}{
  \nl xxx\;
  \nl \KwRet\;}
  \caption{Algorithm with procedure}
\end{algorithm} 

\end{document}

\SetKwProg sets up sub-environments corresponding to a proceedure or an algorithm. \SetKwFunction is used to consitently typeset the names of the funictons. Line numbers are provided by specifying \nl at the beginning of the relevant lines, and the relevant counter is reset before the proceedure, to give the requested numbering.

Related Question