[Tex/LaTex] Creation of counter in reference to section and subsection numbering

countersnumbering

How can I create a counter that when used under a section to count as follows

1.1

1.2

1.3

where the 1 is the section number and when used under a subsection to produce

1.1.1

1.1.2

1.1.3

where 1 is the section number and 1 is the subsection number?

The following is not a MWE. It doesn't compile, it is used to illustrate the use I am looking for.

\documentclass{article}

\begin{document}

\section{Section 1}

\Counter

% Should produce 1.1

\subsection{Subsection 1}

\Counter

% Should produce 1.1.1

\subsection{Subsection 2}

\Counter

% Should produce 1.2.1

\section{Section 2}

\Counter

% Should produce 2.1

\subsection{Subsection 1}

\Counter

% Should produce 2.1.1

\end{document}

Best Answer

Define the counter, say, acntr to be in the reset list of subsection and make a query within \theacntr whether the current subsection counter value is 0 or otherwise.

If 0 use \thesection.\arabic{acntr}, otherwise use \thesubsection.\arabic{acntr}.

Since \stepcounter{section} or \refstepcounter{section} will also reset the subsection counter, the correct value is given at least with LaTeX kernels later than April 2015, otherwise the (outdated) fixltx2e package must be loaded.

\documentclass{article}

\newcounter{acntr}[subsection]

\makeatletter

\renewcommand{\theacntr}{\ifnum0=\c@subsection\thesection.\arabic{acntr}\else\thesubsection.\arabic{acntr}\fi}
\makeatother

\newcommand{\Counter}{%
  \refstepcounter{acntr}%
  \theacntr%
}  

\begin{document}

\section{Section 1}

1.1 $\to$ \Counter

% Should produce 1.1

\subsection{Subsection 1}

1.1.1 $\to$ \Counter

% Should produce 1.1.1

\subsection{Subsection 2}

1.2.1 $\to$ \Counter

% Should produce 1.2.1

\section{Section 2}


2.1 $\to$ \Counter
% Should produce 2.1

\subsection{Subsection 1}


2.1.1 $\to$ \Counter
% Should produce 2.1.1

\end{document}

enter image description here