TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
A minimal working example (MWE) showing the desired type of output would be helpful. – Andrew Swann Mar 15 '13 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. – jason.Z Mar 16 '13 at 0:19
up vote 10 down vote accepted

Here is one version.

Sample output



  \nl xxx\;
  \nl xxx\;
  \nl \proc{}\;
  \nl \KwRet\;}{}
  \nl xxx\;
  \nl \KwRet\;}
  \caption{Algorithm with procedure}


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

share|improve this answer
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. – Marc van Dongen Mar 17 '13 at 13:18
@MarcvanDongen Indeed, that would be my preference too. The reset was added to show the OP's requested formatting. – Andrew Swann Mar 17 '13 at 13:29

Your Answer


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.