# Exercises with links to answers (problem using counter)

Sorry, website won't allow me to ask detailed questions as a comment (neither does it show the formatting toolbar) so adding a new question.

Problem: Trying to create an exercise list (with links to corresponding answers). all answers at end of document. However, I don't want to manually label each question. So, I thought I'll use the question number as the label, but apparently it uses the total number of questions as the label instead. Any help appreciated. Thanks to @CarLaTeX for answering the original question here.

\documentclass{article}
\usepackage{hyperref}% you must load it before the exercise package

\begin{document}

\begin{Exercise}[label={exerciseNumber}]
\end{Exercise}
7

\begin{Exercise}[label={exerciseNumber}]
\end{Exercise}
3

\begin{Exercise}[label={exerciseNumber}]
\end{Exercise}
8
\end{document}


Output (incorrect):

The 'question number' that you are seeking for is stored as a counter, appropriately named as Exercise (at least, for the Exercise environment). You can access the counter by using:

\the\value{Exercise}


So all you need to do is to use this as a label when passing it as an option in \begin{Exercise}. See below for an example.

MWE:

\documentclass{article}
\usepackage{hyperref}% you must load it before the exercise package

\begin{document}
\begin{Exercise}[label={\the\value{Exercise}}]
What is the value of $2+5$? (To see the answer click here:~\refAnswer{\ExerciseLabel})
\end{Exercise}
7

\begin{Exercise}[label={\the\value{Exercise}}]
What is the value of $4-1$? (To see the answer click here:~\refAnswer{\ExerciseLabel})
\end{Exercise}
3

\begin{Exercise}[label={\the\value{Exercise}}]
What is the value of $2\times 4$? (To see the answer click here:~\refAnswer{\ExerciseLabel})
\end{Exercise}
8
\end{document}


You can perhaps make it less cumbersome to type the label, if

(Option 1) you define a macro like \blah:

% Preamble:
\newcommand*{\blah}{\the\value{Exercise}}
% Main document:
\begin{Exercise}[label=\blah]


or

(Option 2) if you're feeling extra lazy, just simply define a new environment:

% In Preamble
\newcounter{Ex}
\newenvironment{Ex}{\begin{Exercise}[name={Exercise},
counter={Ex},
label=\the\value{Ex}]}
{\end{Exercise}}


and then in the main document, call your exercises like so:

% In Main document
\begin{Ex}
What is the value of $2+5$? (To see the answer click here:~\refAnswer{\ExerciseLabel})
\end{Ex}

• Hi everyone. Is it possible to active the hyperlink \refAnswer{\ExerciseLabel} if and only if the answer is non empty ? (else I would like to hide the message (To see the answer cli ...)). – jowe_19 May 12 at 22:11