[Tex/LaTex] Format Code/Pseudocode

formattingpseudocode

In a document containing a lot of other stuff, I have the following code which I have kept in verbatim(for lack of other ideas). As you can see, the alignment doesn't look so good.Image
How do I make it more presentable, so that it becomes more readable, with indentation perhaps(verbatim doesnt seem to handle spaces and tabs)?

\documentclass[]{article}    
\begin{document}    
\begin{verbatim}    

    if (n == 0 || n == 1){    
    return n;        
    }        
    j = 0;    
    for (i = 0; i < n-1; i++){      
    if (arr[i] != arr[i+1]){        
    arr[j] = arr[i];       
    j++;      
    }       
    }      
    arr[j++] = arr[n-1];      


\end{verbatim}    
\end{document}    

Best Answer

Something like this?

\documentclass{book}
\usepackage{listings}

\lstdefinestyle{myListingStyle} 
    {
        basicstyle = \small\ttfamily,
        breaklines = true,
    }

\begin{document}

\begin{lstlisting}[
    style = myListingStyle,
    caption = {Nice listing.}
    ]
    if (n == 0 || n == 1){    
        return n;        
    }        
    j = 0;    
    for (i = 0; i < n-1; i++){      
        if (arr[i] != arr[i+1]){        
            arr[j] = arr[i];       
            j++;      
        }       
    }      
    arr[j++] = arr[n-1]; 
\end{lstlisting}

\end{document}

enter image description here

See Put a grey background behind code extracts in a Latex document (like this site does) for example for adding a background color. It's also possible to load the code from an external file -- just have a look at related questions.

Related Question