Counters in LaTeX (newcounter, setcounter, addtocounter)
LaTeX numbers pages, sections, figures, equations and footnotes with counters. \setcounter{section}{4} sets one, \addtocounter{section}{1} changes it by an amount, and \newcounter{name} creates your own.
Set and change a counter
The counters are named like the object they count: page, chapter, section, subsection, figure, table, equation, footnote, and enumi for the first level of a numbered list. A heading raises its counter before printing it, so after \setcounter{section}{4} the next section is 5.
\setcounter{section}{4}
\section{Results}
This section has the number 5.
\addtocounter{footnote}{2}
Text\footnote{This footnote has the number 3.}Create and print your own counter
\newcounter{exercise} creates the counter with the value 0. \stepcounter raises it by one, and \theexercise prints the value.
\newcounter{exercise}
\stepcounter{exercise}
Exercise \theexercise: Add two numbers.
\stepcounter{exercise}
Exercise \theexercise: Multiply two numbers.Change how a counter is printed
For every counter there is a command \the plus its name that prints it. Redefine it with \arabic (1), \roman (i), \Roman (I), \alph (a), \Alph (A) or \fnsymbol (symbols such as an asterisk and a dagger).
\renewcommand{\thesection}{\Roman{section}}
\renewcommand{\thesubsection}{\thesection.\alph{subsection}}
\section{Introduction}
\subsection{Background}
This subsection has the number I.a.Restart a counter in every section
\counterwithin{equation}{section} resets the equation counter at every \section and prints the section number in front, as in (2.1). \counterwithout undoes such a link. For a new counter, the optional argument does the reset: \newcounter{exercise}[section].
\counterwithin{equation}{section}
\section{First}
\begin{equation} a = b \end{equation}
\section{Second}
\begin{equation} c = d \end{equation}A counter you can refer to
\refstepcounter raises the counter and makes it the target of the next \label, so \ref prints its value.
\newcounter{exercise}
\newcommand{\exercise}{\par\medskip\refstepcounter{exercise}%
\noindent\textbf{Exercise \theexercise.} }
\exercise\label{ex:sum} Add two numbers.
\exercise Use the result of exercise~\ref{ex:sum}.Pitfalls
\alphand\Alphend at 26 and\fnsymbolat 9. A higher value stops with "Counter too large", see Counter too large.- Where LaTeX expects a number, write
\value{page}, not\thepage:\setcounter{exercise}{\value{section}}.\thepageis the printed form and can be a roman numeral. \setcounterand\addtocounteract globally, also inside an environment or a group.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- How-to Page numbers in LaTeX
- How-to Number equations in LaTeX
- How-to Define your own commands in LaTeX
- Error Counter too large
- Error Missing number, treated as zero