3

I have to include algorithms in a paper and they must appear as follows:

[A]     X ← X-1
        Y ← Y+1
        IF X ≠ 0 GOTO A

so I am trying to replicate this exactly, exploring some new packages as well but unfortunately it seems I can't get the hang of it. I'm finding particularly difficult including the [A] label before the statement and then the space on the next line. Is there any formatting tip I can follow or any package I can include?

Edit: For the assignment part I would love to use the math mode, mostly because there are lots of math signs I have to include, as for the appearence it should really be rendered as shown above: the label on the left, if present and if not there should be a nice space and all the statements must be stacked and aligned.

haunted85
  • 1,295
  • Have you tried the alltt package and environment? – recluze Jan 11 '13 at 15:48
  • What about a tabular? – egreg Jan 11 '13 at 15:50
  • ... or even a tabbing environment? – guillem Jan 11 '13 at 15:54
  • @egreg if I used tabular there should be a line between the label and the statement, shouldn't it? I definitely don't want that. – haunted85 Jan 11 '13 at 15:55
  • 1
    @haunted85 Why? \begin{tabular}{@{}ll@{}} will give you the alignment you need. Also tabbing could be a possibility, as @guillem says. Can you add some more details? Should it use math mode for the "assignment parts"? What about the label? Should the whole thing be centered or flush left? – egreg Jan 11 '13 at 15:57
  • @egreg sorry but I really am a noob when it comes to macros... I hope you don't mind if I ask how do I use your snippet when I want to insert a statement without label, making sure the proper space is left? – haunted85 Jan 11 '13 at 16:03

1 Answers1

3

I'll make some assumptions about what you want.

  • The label is in text form
  • The second part of the line is in math mode
  • The whole thing should be flush left

So, let's try:

\documentclass{article}

\usepackage{array}

\newenvironment{algodesc}
  {\begin{flushleft}\begin{tabular}{@{} l @{\hspace{3em}} >{$}l<{$} @{}}}
  {\end{tabular}\end{flushleft}}

\newcommand{\algolabel}[1]{[#1]}
\newcommand{\keyw}[1]{\textup{#1}}
\newcommand{\goto}[1]{\textup{GOTO #1}}

\begin{document}

Some text before the algorithm, explaining what it does
and then the algorithm itself:
\begin{algodesc}
\algolabel{A} & X \gets X-1 \\
              & Y \gets Y+1 \\
              & \keyw{IF}\ X\ne 0\ \goto{A}
\end{algodesc}
and some text after it.

\end{document}

Language keywords can be used in the argument of \keyw; the special one "GOTO" is in \goto that takes the label as argument.

You can also consider specialized package such as algpseudocode.

enter image description here

egreg
  • 1,121,712
  • 1
    Yes, thank you so much for your help! :) If you are willing and have time, will you please explain what you have put in the \newenvironment part? – haunted85 Jan 11 '13 at 16:23