6

I added some pseudocode to my document in this style:

\usepackage{algpseudocode}

\begin{algorithmic}[1]
\If {$i\geq maxval$}
\State $i\gets 0$
\Else
\If {$i+k\leq maxval$}
    \State $i\gets i+k$
\EndIf
\EndIf
\end{algorithmic}

I want my pseudocode to appear in a box, i.e. framed.

I tried

\framebox{ 
    \begin{algorithmic}[1] ...     
    \end{algorithmic} 
}

but that gave me tons of errors and didn't divide the code on multiple lines.

How can I frame my pseudocode?

2 Answers 2

8

Using \varwidth you can set an upper limit as the width of the line minus the space taken up by the box margins, but allow it to shrink if possible to the longest line of the display

enter image description here

\documentclass{article}
\usepackage{varwidth}

\usepackage{algpseudocode}

\begin{document}
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\begin{algorithmic}[1]
\If {$i\geq maxval$}
\State $i\gets 0$
\Else
\If {$i+k\leq maxval$}
    \State $i\gets i+k$
\EndIf
\EndIf
\end{algorithmic}
\end{varwidth}% 
}

\end{document}
0
6

You only need to adjust the minipage's width to avoid overfull.

Edit: adding some comments from David.

\noindent\fbox{%
\begin{minipage}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\begin{algorithmic}[1]
\If {$i\geq maxval$}
\State $i\gets 0$
\Else
\If {$i+k\leq maxval$}
    \State $i\gets i+k$
\EndIf
\EndIf
\end{algorithmic}
\end{minipage}% 
}
10
  • Thanks for the fast answer, that solves my issue. Which parameter instead of \linewidth has to be used in order to limit the width to the necessary amount, so that it just frames the content?
    – bogus
    Commented Jan 10, 2013 at 14:45
  • @bogus, this is a good question. Now we have to wait the experts... sorry.
    – Sigur
    Commented Jan 10, 2013 at 14:46
  • 1
    Solved: \begin{minipage}{0.5\columnwidth} where 0.5 is an arbitrary factor to scale the width
    – bogus
    Commented Jan 10, 2013 at 14:48
  • 1
    you need \fbox{% and \end{minipage}% otherwise you have a word space at start and end of a box then use \dimexpr\linewidth-2\fboxsep-2\fboxrule\relax as the width to allow for the rule and padding on either side and use \noindent\fbox so the whole thing is flush left not indented. Commented Jan 10, 2013 at 14:50
  • 1
    It isn't necessary but if you use it anyway then you don't need to know the internals of minipage. the scanning of the arithmetic expression of \dimexpr may be stopped by many things but until it sees an unexpandable token that is not allowed there it will keep expanding ahead looking for more infix expressions. If it sees \relax not only does it stop looking for more of the expression it removes the \relax as part of the expression syntax so that the \relax only stops the length expression and is not actually passed on to the scanner. Commented Jan 10, 2013 at 15:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .