# How to ref the last number in a newcounter [duplicate]

In the following, I want to ref the last number. Thanks in advance

 \documentclass{article}
\usepackage{xcolor,graphicx,amssymb}
\usepackage[usestackEOL]{stackengine}
\newcommand{\repeatntimes}[2]{%
\newcount\i%
\i=0%
\newtoks\ans%
\loop%
\ans=\expandafter{\the\ans #2}%
\ifnum\i<#1\repeat%
\the\ans%
}
\newcommand{\countRepeatntimes}[2]{%
\newcount\i%
\i=0%
\newtoks\ans%
\loop%
\ans=\expandafter{\the\ans #2}%
\ifnum\i<#1\repeat%
\the\ans%
}
\newcommand\numberbox[1]{\colorbox{black!50}{\makebox[1em]{\textcolor{white}{#1}}}}
\newcommand\letterbox[2][green!10]{\fcolorbox{blue}{#1}{\makebox[1.2em]{#2}}}
\newcounter{problem}
\newcounter{choice}
\newcommand{\generateQs}[2][0]{%
\countRepeatntimes{#2}{\stepcounter{problem}\savestack{\Prob}{%
\numberbox{\theproblem}}%
\setcounter{choice}{0}%
\repeatntimes{\numexpr\NumberOfChoices-1}{\stepcounter{choice}%
\if\Alph{choice}#1\relax%
\savestack{\Prob}{\stackunder{\Prob}{\letterbox[red!10]{\Alph{choice}}}}%
\else%
\savestack{\Prob}{\stackunder{\Prob}{\letterbox{\Alph{choice}}}}%
\fi%
}\Prob\kern7pt%
}%
}
\def\NumberOfChoices{4}
\def\makegrid#1#2#3\relax{%
\generateQs[#1]{1}\ifx\relax#3\else\makegrid#3\relax\fi%
}
\begin{document}

The exam contains (ref the last number) MCQs

\end{document}


## marked as duplicate by egreg cross-referencing StackExchange.ready(function() { if (StackExchange.options.isMobile) return; $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() { var$hover = $(this).addClass('hover-bound'),$msg = $hover.siblings('.dupe-hammer-message');$hover.hover( function() { $hover.showInfoMessage('', { messageElement:$msg.clone().show(), transient: false, position: { my: 'bottom left', at: 'top center', offsetTop: -7 }, dismissable: false, relativeToBody: true }); }, function() { StackExchange.helpers.removeMessages(); } ); }); }); Jun 14 '16 at 10:06

• Off-topic: \bf and friends are 20+ years obsolete as far as LaTeX is concerned. – cfr May 14 '16 at 22:47
• \AtEndDocument{\addtocounter{problem}{-1}\refstepcoundt{problem}\label{lastproblem}} should do it. – John Kormylo May 15 '16 at 0:01
• This is ridiculous. This is basically a completely different question now. This is the third completely different question you've posted. I answered the first. I answered the second. Lest I be drawn into the madness which is answering the nth, I draw the line at considering the third. – cfr May 15 '16 at 0:11

Similarly to LastPage you can add in the preamble of the document

\makeatletter
\def\lastproblem@putlabel{%
\immediate\write\@auxout{%
\string\newlabel{LastProblem}{{\@arabic\c@problem}{}{}{}{}}}}
\AtEndDocument{\lastproblem@putlabel}
\makeatother


and then

...
The exam contains \ref{LastProblem} problems.
...


in the body of the document.