4

I want to reference to a line where a for/while-loop starts. However, with the normal \label command I cannot set a label in the respective line. How else can I reference to the beginning of, e.g., a while-loop? In particular for the example below, how can I create a reference for lines 2-6?


\usepackage[linesnumbered]{algorithm2e}

\begin{document}

Reference to Lines \ref{alg:taskA}-\ref{alg:taskC}. How do I achieve a reference to lines 2-6?

\vspace{2em}

\begin{algorithm}[H]
\KwData{some data}
\KwResult{some result}
initialization\;
\While{termination condition not satisfied}{
Do task A\label{alg:taskA}\\
Do task B\label{alg:taskB}\\
Do task C\label{alg:taskC}\\
}
\end{algorithm}

\end{document}

enter image description here

1 Answer 1

3

Well, simply add an new label after the closing } for the while loop: \label{alg:endWhile} and add an label \label{alg:startWhile} for the start of the while loop ...

So with the following mwe

\documentclass{article}

\usepackage[linesnumbered]{algorithm2e}


\begin{document}

Reference to Lines~\ref{alg:taskA}--\ref{alg:taskC}. How do I achieve a reference to lines 2-6?

Like~\ref{alg:startWhile}--\ref{alg:endWhile}? % <===========================

\vspace{2em}

\begin{algorithm}[H]
\KwData{some data}
\KwResult{some result}
initialization\;
\While{termination condition not satisfied}{\label{alg:startWhile} % <===========================
Do task A\label{alg:taskA}\\
Do task B\label{alg:taskB}\\
Do task C\label{alg:taskC}\\
}\label{alg:endWhile} % <===============================================
\end{algorithm}

\end{document}

you get the wished result:

result

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.