This is to show how to use a counter in LaTeX. Nothing fancy. You will find using a counter is really convenient when necessary. The followings are the four most important commands. Let’s name our counter ctProb.
- To define a new counter:
\newcounter{ctProb} - To initialize the counter:
\setcounter{ctProb}{0} - To increment the counter:
\addtocounter{ctProb}{1} - To print out the counter:
\arabic{ctProb}
Example usage: Let’s imagine that you are an instructor of a course. You are going to assign homework problems. In LaTeX file, you would like to write as simple as:
\problem This is the first homework problem..
\solution This is the hidden solution..
\problem This is another problem..
\solution This is the solution to the problem..
Of course, you have to define the \problem and \solution command. In the \problem command there should be a counter associated to it, such that you don’t need to manually number the problems (just like the \section command). This is what you have to put in the preamble. Simple!
\newcounter{ctProb}
\setcounter{ctProb}{0}
\newcommand{\problem}{%
\addtocounter{ctProb}{1}%
\paragraph{Problem \arabic{ctProb}}}
\newcommand{\solution}{%
\emph{Solution}: \hspace{2mm}}
Try it!
0 Responses to “A Simple Counter”