latex

How to Insert a Code Block in LaTeX

The code block in every document helps a reader understand the difference between codes and texts. Source code blocks are also helpful when tangling a source file or generating bitmap graphics or PDF snippets.

Document processors like LaTeX provide a simple method to add a code block in the research paper. So, in this tutorial, we will explain the different ways you can try to insert a code block in LaTeX.

How to Insert a Code Block in LaTeX?

There are multiple ways to insert a code block and write codes in LaTeX so let’s start with the basic example:

\documentclass{article}
\begin{document}
\begin{verbatim}
#include <iostream>

int main() { std::cout << "Hello World!";
    return 0;}
\end{verbatim}
\end{document}

Output

If you want to highlight and colorize the inserted codes, please use the listings \usepackage. Here is the simple source code:

\documentclass{article}
\usepackage{listings}
\usepackage{color}
\begin{document}
\lstset{frame=tb,
  language=c++,
  aboveskip=5mm,
  belowskip=5mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=none,
  numberstyle=\tiny\color{blue},
  keywordstyle=\color{red},
  commentstyle=\color{pink},
  stringstyle=\color{green},
  breaklines=true,
  breakatwhitespace=true,
  tabsize=3}

\begin{lstlisting}
#include <iostream>

int main() { std::cout << "Hello World!";
    return 0;}

\end{lstlisting}
\end{document}

Output

You can change the color, language type, line spacing, and many more from the above code.

The minted \usepackage to insert the code block is supported, and here is the example related to it:

\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{C++}
#include <iostream>
int main() { std::cout << "Hello World!";
return 0;}
\end{minted}
\end{document}

Output

Please use the following source code to insert inline code into the document:

\documentclass{article}
\usepackage{minted}
\begin{document}
There is change in the \mintinline{c++}|int main()|.
\end{document}

Output

Moreover, there is a specific source code you can use to insert a code block specifically for the Python language:

\documentclass{article}  
\usepackage{pythonhighlight}
\begin{document}
Evaluate the sum of two numbers in Python:
\begin{python}
n1 = 5
n2 = 6
sum = n1 + n2
print('The sum of {0} and {1} is {2}'.format(n1, n2, sum))
\end{python}
\end{document}

Output

Conclusion

In this tutorial, we have explained various ways to insert a code block in LaTeX. Inserting code blocks can help you highlight the codes in the document so that a reader can understand them better.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.