# Algorithm return statement does not begin on new line

I have the following code for displaying an algorithm:

\begin{algorithm}
\caption{Compute index of nearest grid point given particle position (1D)}
\label{nearestGridPoint}
\begin{algorithmic}[1]
\Function{FindMeshIndex}{$position$, $nGrid$}
\State $index=math.floor(position+0.5)+((nGrid/2)+1)$
\If{$index=-1$}
\State $index=nGrid-1$
\EndIf
\Return $index$
\EndFunction
\end{algorithmic}
\end{algorithm}


The output places the endif and return statements on the same line. Is there some formatting nuance that I have missed?

## migrated from stackoverflow.comApr 14 '15 at 17:35

This question came from our site for professional and enthusiast programmers.

• Welcome to TeX.sx! Your post was migrated here from another Stack Exchange site. Please register on this site, too, and make sure that both accounts are associated with each other (by using the same OpenID), otherwise you won't be able to comment on or accept answers or edit your question. – Werner Apr 14 '15 at 18:09

\Return doesn't issue a new line in the algorithm. You could force this through a redefinition:

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\newcommand{\vars}{\texttt}
\newcommand{\func}{\textrm}
\let\oldReturn\Return
\renewcommand{\Return}{\State\oldReturn}
\begin{document}
\begin{algorithm}
\caption{Compute index of nearest grid point given particle position (1D)}
\label{nearestGridPoint}
\begin{algorithmic}[1]
\Function{FindMeshIndex}{$\vars{position}, \vars{nGrid}$}
\State $\vars{index} = \func{math.floor}(\vars{position} + 0.5) + ((\vars{nGrid}/2)+1)$
\If{$\vars{index} = -1$}
\State $\vars{index} = \vars{nGrid} - 1$
\EndIf
\Return $\vars{index}$
\EndFunction
\end{algorithmic}
\end{algorithm}
\end{document}


\Return has been redefined to issue a \State first.

I've taken the liberty of defining \vars (for variables) and \func (for functions) which could improve your algorithm display.

• Or, if you only use it once you could simply write "\State\Return" instead of "\Return". – marczoid Oct 18 '17 at 19:19
\State \Return your-text


will fix it.

• Welcome to TeX.SX! This is exactly the same as the other answer did. – TeXnician Jan 9 '18 at 6:17
• I disagree with downvotes. The other answer fails to suggest this simple strategy. – egreg Jan 9 '18 at 7:17

In preamble:

\algrenewcommand{\Return}{\State\algorithmicreturn~}

• How does this differ from the previous answers? – TeXnician May 9 '18 at 12:01
• The two previous answers say: 1. \let\oldReturn\Return; \renewcommand{\Return}{\State\oldReturn} 2. \State \Return your-text – Alexandre Huat May 14 '18 at 9:09

Another simple solution is to add \\ at the end of the previous State.

\State bla.. bla.. bla.. \\
\Return bla..

• Welcome to TeX - LaTeX! This works here. It would be nice if you could make this into a complete small document and upload a picture of the output too. – Andrew Swann May 25 at 9:18