# Putting pseudocode in a framed box

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?

-

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

\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}

-

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

\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}%
}

-
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 Jan 10 '13 at 14:45
@bogus, this is a good question. Now we have to wait the experts... sorry. –  Sigur Jan 10 '13 at 14:46
Solved: \begin{minipage}{0.5\columnwidth} where 0.5 is an arbitrary factor to scale the width –  bogus Jan 10 '13 at 14:48
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. –  David Carlisle Jan 10 '13 at 14:50
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. –  David Carlisle Jan 10 '13 at 15:25