Home > Latex > FAQ > Latex - FAQ > How to write algorithm and pseudocode in Latex ?\usepackagealgorithm,\usepackage

# How to write algorithm and pseudocode in Latex ?\usepackage{algorithm},\usepackage{algorithmic}

Friday 31 December 2010,

Keywords: , , .

We must use the following packages

\usepackage{algorithm} \usepackage{algorithmic}

Here is an exemple:

\begin{algorithm} \caption{Calculate $y = x^n$} \begin{algorithmic} \REQUIRE $n \geq 0 \vee x \neq 0$ \ENSURE $y = x^n$ \STATE $y \leftarrow 1$ \IF{$n < 0$} \STATE $X \leftarrow 1 / x$ \STATE $N \leftarrow -n$ \ELSE \STATE $X \leftarrow x$ \STATE $N \leftarrow n$ \ENDIF \WHILE{$N \neq 0$} \IF{$N$ is even} \STATE $X \leftarrow X \times X$ \STATE $N \leftarrow N / 2$ \ELSE[$N$ is odd] \STATE $y \leftarrow y \times X$ \STATE $N \leftarrow N - 1$ \ENDIF \ENDWHILE \end{algorithmic} \end{algorithm}

Here are useful commands

### Single line statements

\STATE <text>

### If-statements

\IF{<condition>} <text> \ENDIF \IF{<condition>} <text> \ELSE <text> \ENDIF \IF{<condition>} <text> \ELSIF{<condition>} <text> \ELSE <text> \ENDIF

### For-loops

There are two forms

\FOR{<condition>} <text> \ENDFOR \FORALL{<condition>} <text> \ENDFOR

### While-loops

\WHILE{<condition>} <text> \ENDWHILE

### Repeat until condition

\REPEAT <text> \UNTIL{<condition>}

### Infinite loops

\LOOP <text> \ENDLOOP

### Precondition

\REQUIRE <text>

### Postcondition

\ENSURE <text>

### Returning variables

\RETURN <text>

### Printing variables

\PRINT <text>

Note: Due to a bug, the algorithmic package is not compatible with hyperref.

## Forum posts

• The following:

\beginalgorithm
\caption$\qquad t3$ generator based on ratio-of-uniforms method
\beginalgorithmic
\REPEAT Generate iid uniform $[-1,1]$ random variables $U,V$
\UNTIL $U^2+V^2 \le 1$
\RETURN $X \leftarrow \sqrt3\displaystyle\fracV1+U$
\endalgorithmic
\endalgorithm

yields the correct output, but an error code is output referring to the
"\RETURN" line. Why is that?

• The code isn’t running on my document. The skeleton is given bellow
\documentclass[journal, a4paper]IEEEtran
\makeglossary
\usepackagealgorithm, algorithmic
\begindocument
....
....
\enddocument
It’s showing the commands like \STATE and \ENSURE as undefined control sequences. Everything else in the document, including the math symbols are perfect. Are you sure that no other package is necessary?