The Elegant Way to Write Code in Latex

It is probably a weird problem for one to paste code in LaTex. However, I have such demands, here are some useful approaches to writing code in Latex.

1. Write Code with Markdown in Latex

This is the simplest way to write code in my opinion. All one needs to do is include a markdown package and start writing it.

Example [1]:

\usepackage[settings]{markdown}
\begin{markdown}
    template <typename T>
    int findIndex(const T arr[], int size, const T& scalar) {
        for (int i = 0; i < size; ++i) {
            if (arr[i] == scalar) {
                return i;
            }
        }
        return -1; 
    }
\end{markdown}

It will look like this: Example 1 The issue with this way is it doesn’t have syntax highlighting!

For more information on writing markdown in LaTex, you can check the guide on Overleaf.

2. Write Code with Minted Package

The “minted” package was created to display code in LaTex, it’s pretty simple to use, here is a basic usage:

\usepackage{minted}
\begin{minted}{cpp}
template <typename T>
int findIndex(const T arr[], int size, const T& scalar) {
    for (int i = 0; i < size; ++i) {
        if (arr[i] == scalar) {
            return i;
        }
    }
    return -1; 
}
\end{minted}

Example 2

Also, we have a more fancy way to display the code, the minted package supports stylesheets, for example, we have:

\usepackage{xcolor}
\usepackage{minted}
\usemintedstyle{monokai}
\definecolor{LightDark}{gray}{0}
\begin{minted}[bgcolor=LightDark]{cpp}
template <typename T>
int findIndex(const T arr[], int size, const T& scalar) {
    for (int i = 0; i < size; ++i) {
        if (arr[i] == scalar) {
            return i;
        }
    }
    return -1; 
}
\end{minted}

Example 3

For more information on the minted package, check out the guide on Overleaf