# Subroutine in algorithm2e

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?

• A minimal working example (MWE) showing the desired type of output would be helpful. Mar 15, 2013 at 10:45
• @AndrewSwann I do not have a working example... If I had, I would not ask the question... I need an example to write an algorithm, which has a subroutine/function inside the algorithm. Mar 16, 2013 at 0:19

Here is one version.

\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.

• It may be better if you don't reset the line numbers in the same algorithm. That way it's clear which lines are meant when you refer to Lines 1 and 2.
– user10274
Mar 17, 2013 at 13:18
• @MarcvanDongen Indeed, that would be my preference too. The reset was added to show the OP's requested formatting. Mar 17, 2013 at 13:29