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.}
Result
The compiled example

Open in the editor

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.
Result
The compiled example

Open in the editor

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.
Result
The compiled example

Open in the editor

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}
Result
The compiled example

Open in the editor

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}.
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages