Aligning Pseudocode In LaTeX


Answer :

I have never used an algorithm package in Latex, what I'd do is use the verbatim environment and manually indent the code in the text editor.

\begin{verbatim} 1 y=0 2 for i = n downto 0 3     y = a_i + x * y \end{verbatim} 

This will put exactly what you type in the environment in the output, including whitespace. If you need fancy Latex (like subscript and such) check the alltt package.

Info on Verbatim


If I were you and I was absolutely sure that the algorithmic package is not the way to go, I'd use something like this:

\begin{align*}   &y = 0 \\   &\text{for $i = n$ downto 0} \\   & \hspace{1cm} y = a_i + x * y \end{align*} 

This results in

rendering of the above LaTeX snippet


Edit 2: Sorry, from your code excerpt and another answer, I somehow thought you wanted verbatim text.

I have had success using algorithmicx. It is customizable for your needs.

Documentation (PDF)

\usepackage{algorithm} \usepackage[noend]{algpseudocode}  \begin{algorithm} \begin{algorithmic} \State $y \gets 0$ \For{$i \gets n, 0$}   \State $y \gets a_i + xy$ \EndFor \end{algorithmic} \caption{Example algorithm.} \label{examplealgorithm} \end{algorithm} 

Edit 1: Looking through some of my old reports, here are two example customizations for the Verbatim environment. See the documentation PDF (link below) for more details.

\usepackage{fancyvrb} \usepackage{color} \RecustomVerbatimEnvironment{Verbatim}{Verbatim}{fontsize=\small,    frame=single, rulecolor=\color{blue}, framerule=0.5mm, framesep=1mm,     xleftmargin=2mm} %\RecustomVerbatimEnvironment{Verbatim}{Verbatim}{fontsize=\scriptsize,     %numbers=left, numbersep=8pt, baselinestretch=1, xleftmargin=5mm,     %commandchars=\~\{\}}  \begin{Verbatim} y = 0 for i = n downto 0     y = a_i + x * y \end{Verbatim} 

Original: I recommend the Verbatim environment from the fancyvrb package, not to be confused with the built-in verbatim environment. It does exactly what you need.

Documentation. (PDF)


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable