[Tex/LaTex] Minted: aligning code fragments left

alignmenthorizontal alignmentminted

I've written two small code fragments in minted, but when I compile the document, the code fragments are aligned in such a way that one of the code fragments spills off the page, as seen below:

enter image description here

This is the code that I'm using.

\noindent\underline{Loop 1}
    \begin{figure}[!h]
        \begin{minted}[frame=lines, framesep=4mm]{C}
            void loop1(void){
                for (int i = 0; i < N; i++){
                    for (int j = N - 1; j > i; j--){
                        a[i][j] += cos(b[i][j]);
                    }
                }
            }
    \end{minted}
\end{figure}

\noindent\underline{Loop 2}
    \begin{figure}[!h]
        \begin{minted}[frame=lines, framesep=4mm]{C}
            void loop2(void){
                double rN2 = 1.0/(double)(N * N);

                for (int i = 0; i < N; i++){
                    for (int j = 0; j < jmax[i]; j++){
                        for (int k = 0; k < j; k++){
                            c[i] += (k+1) * log (b[i][j]) * rN2;
                        }
                    }
                }
            }
        \end{minted}
    \end{figure}

I've tried using a center environment and flushleft and other similar ones, but none were able to change it. My latest attempts were to put the minted environment inside a figure, or minipage, but those didn't help either me control where the code fragments were being placed. I basically just want the code fragments to be left aligned, so they fit fully on the page.

Best Answer

Remember, you're in a verbatim context, so everything you type goes to the output, spaces included. What you're seeing is the combined indentation of your LaTeX code with your C code.

You can use the gobble option to specify how many characters should be removed, or the autogobble to let minted decide how many should be removed:

\documentclass{article}

\usepackage{minted}

\begin{document}

\noindent\underline{Loop 1}
    \begin{figure}[!h]
        \begin{minted}[frame=lines, framesep=4mm, autogobble]{C}
            void loop1(void){
                for (int i = 0; i < N; i++){
                    for (int j = N - 1; j > i; j--){
                        a[i][j] += cos(b[i][j]);
                    }
                }
            }
    \end{minted}
\end{figure}

\noindent\underline{Loop 2}
    \begin{figure}[!h]
        \begin{minted}[frame=lines, framesep=4mm, gobble=12]{C}
            void loop2(void){
                double rN2 = 1.0/(double)(N * N);

                for (int i = 0; i < N; i++){
                    for (int j = 0; j < jmax[i]; j++){
                        for (int k = 0; k < j; k++){
                            c[i] += (k+1) * log (b[i][j]) * rN2;
                        }
                    }
                }
            }
        \end{minted}
    \end{figure}

\end{document}

enter image description here