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 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
add comment

1 Answer

up vote 4 down vote accepted

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.

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
add comment

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.