There are a few ways to do this, but one of the simplest ways to pretty-print code in LaTeX documents is to use the listings package. The package can be configured to use specific colors for different parts of the code, with many programming languages supported.

The following document will display code for both C++ and Java, with settings provided for the most common configuration:

\usepackage{xcolor} % for setting colors

% set the default code style
    frame=tb, % draw a frame at the top and bottom of the code block
    tabsize=4, % tab space width
    showstringspaces=false, % don't mark spaces in strings
    numbers=left, % display line numbers on the left
    commentstyle=\color{green}, % comment color
    keywordstyle=\color{blue}, % keyword color
    stringstyle=\color{red} % string color


\begin{lstlisting}[language=C++, caption={C++ code using listings}]
#include <iostream>
int main()
    // print hello to the console
    std::cout << "Hello, world!" << std::endl;
    return 0;

\begin{lstlisting}[language=Java, caption={Java code using listings}]
public class Hello
    public static void main(String[] args)
        // print hello to the console
        System.out.println("Hello, world!");


This will produce the following document:

LaTeX document with Java and C++ code syntax highlighting

The package is much more flexible than the example above shows; see the full documentation for more details.

  1. Yogesh says:

    i want to how to write c++ code in latex.