# How to keep comments on their own line with algorithmicx?

I'm trying to add comments on their own line. the default behaviour of \Comment{} is to place the comment on the same line as a \State. My current hack is to just do

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup$algorithm${labelformat=empty}
\begin{document}
\begin{algorithm}
\caption{Init}
\begin{algorithmic}$1$
\State // Here is a comment the way I want it.
\State $x \gets y$
\end{algorithmic}
\end{algorithm}
\end{document}]

Desired output:

Is there a proper way to do this? What about making the comment italicized so that it's a little less intrusive?

• Please make a minimal working example (MWE) and a image of the desired result. Jul 7, 2017 at 13:00
• OK. I expanded the code and added an image. Jul 7, 2017 at 14:35

## 2 Answers

I fixed some errors in the code:

• replaced the 2 occurrences of $...$ with [...]
• deleted the last character ]

I added the \textit command to get the comment italicized.

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup[algorithm]{labelformat=empty}

\begin{document}
\begin{algorithm}
\caption{Init}
\begin{algorithmic}[1]
\State // \textit{Here is a comment the way I want it.}
\State $x \gets y$
\end{algorithmic}
\end{algorithm}
\end{document}

You could also define a command for your comment type (\CommentLine):

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup[algorithm]{labelformat=empty}

\newcommand{\CommentLine}[1]{
\State // \textit{#1}
}

\begin{document}
\begin{algorithm}
\caption{Init}
\begin{algorithmic}[1]
\CommentLine{Here is a comment the way I want it.}
\State $x \gets y$
\end{algorithmic}
\end{algorithm}
\end{document}

Redefine the way algorithmicx's \Comment works using

\algrenewcommand\algorithmiccomment[1]{// {\itshape #1}}

The default behaviour is to insert \hfill $$\triangleright$$, which puts the comment flush with the right margin.

\documentclass{article}

\usepackage{algpseudocode,algorithm}

\usepackage{caption}
\captionsetup[algorithm]{labelformat=empty}

\algrenewcommand\algorithmiccomment[1]{// {\itshape #1}}

\begin{document}

\begin{algorithm}
\caption{Init}
\begin{algorithmic}[1]
\State // Here is a comment the way I want it.
\State $x \gets y$
\State \Comment{Here is a comment the way I want it.}
\end{algorithmic}
\end{algorithm}

\end{document}