[Tex/LaTex] How to create a new counter for an a new environment that is in sync with subsections

countersenvironmentsnumberingsectioning

I want to create an example environment with a counter which will be in sync with my subsections. So I'll have:

subsection 3.2
lemma 3.2
example 3.2
example 3.3
lemma 3.3

subsection 3.3
example 3.3
example 3.4

I find it hard to understand the \newcounter command and how it works. Plus, is there a command for \onsectionchange – so I can do (in pseudo code):

\onsubsectionchange{
%example counter := subsection counter
}

Best Answer

Use a theorem environment. Besides classical theorems, such numbered environments can be used for lemmas, definitions, examples, and more. So you don't have to take care of defining environments and counter adjustments.

A simple example:

\documentclass{article}
\newtheorem{example}{Example}[subsection]
\begin{document}
\section{One}
\subsection{One}
\begin{example}
Text
\end{example}
\end{document}

There are various theorem packages which provides ways for customizing such numbered environments, see: Theorem packages: which to use, which conflict.

Related Question