Generating Table of Contents

Introduction

Welcome back to Document Structure and Layout! In the previous lesson, you learned how to organize a LaTeX document into sections, subsections, and subsubsections with automatic numbering. That heading hierarchy is exactly the foundation we need for this second lesson, because now we will use it to generate a table of contents directly from those headings.

By the end of this lesson, you will know how to produce a table of contents with a single command, understand why LaTeX needs more than one compilation pass to build it, and control which headings appear in it using starred section variants.

What a Table of Contents Does for Your Reader

Open any textbook or lengthy report and one of the first things you see is a table of contents — a list of every major heading paired with its page number. This simple navigation aid lets readers jump straight to the part they need instead of scrolling or flipping through pages.

In a word processor, you might build this list by hand, typing each heading title and page number yourself. The obvious problem is that every time you edit the document, the page numbers can shift and the list goes stale. LaTeX solves this by generating the table of contents automatically from the sectioning commands you already have in your document. You write your headings once, and LaTeX keeps the table of contents synchronized for you.

The `\tableofcontents` Command

Producing a table of contents in LaTeX requires just one command: \tableofcontents. You place it in the document body at the point where you want the list to appear — typically right after \begin{document} and before your first section:

latex
\documentclass{article}
\begin{document}

\tableofcontents

\section{Introduction}
Some introductory text goes here.

\section{Methods}
A description of the methods used.

\subsection{Data Collection}
Details about how data was collected.

\section{Results}
Our main findings.

\end{document}

When this document is fully compiled, LaTeX reads every \section and \subsection heading, collects their titles and page numbers, and places a formatted list at the location of \tableofcontents. The output looks something like this:

Compiled output showing a table of contents with three sections and one subsection, each with a page number

Notice that you did not type any of those entries yourself. LaTeX pulled each title and page number directly from the heading commands in your source file.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal