[Tex/LaTex] Putting pseudocode in a framed box

framedpseudocode

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?

Best Answer

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}
Related Question