How to format for loop

If you're interested in typesetting algorithmic code, there are a number of choices. You can use a pseudocode environment algpseudocode offered by algorithmicx. Here's a short example from the algorithmicx documentation (with a pseudocode for loop added):

enter image description here

\documentclass{article}
\usepackage{algorithm}% http://ctan.org/pkg/algorithm
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\begin{document}
\begin{algorithm}
  \caption{Euclid’s algorithm}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
      \State $r\gets a\bmod b$
      \While{$r\not=0$}\Comment{We have the answer if r is 0}
        \State $a\gets b$
        \State $b\gets r$
        \State $r\gets a\bmod b$
      \EndWhile\label{euclidendwhile}
      \For{\texttt{<some condition>}}
        \State \texttt{<do stuff>}
      \EndFor
      \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}
\end{document}

The algorithms bundle supplied the algorithm floating environment.

Alternatively, the de-facto program typesetting package is listings. The examples, usage and language support is vast. An abundance of examples is contained within the listings documentation.


If you just want to print the statement, then something like

\[
\text{for $k = 1$, $k{+}{+}$, while $k < i$}
\]

will set it in a displayed format (remember to call \usepackage{amsmath} in the preamble). If it's as an item in an enumerate, then

\item for $k = 1$, $k{+}{+}$, while $k < i$

is sufficient.

The only subtle point is to enclose the + symbols between braces, in order to avoid undesired spacings.


\documentclass{article}
\usepackage{algorithm,algpseudocode}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}

\begin{document}

\begin{algorithm}[H] 
\caption{Sum of Array Elements}
\label{alg:loop}
\begin{algorithmic}[1]
\Require{$A_{1} \dots A_{N}$} 
\Ensure{$Sum$ (sum of values in the array)}
\Statex
\Function{Loop}{$A[\;]$}
  \State {$Sum$ $\gets$ {$0$}}
    \State {$N$ $\gets$ {$length(A)$}}
    \For{$k \gets 1$ to $N$}                    
        \State {$Sum$ $\gets$ {$Sum + A_{k}$}}
    \EndFor
    \State \Return {$Sum$}
\EndFunction
\end{algorithmic}
\end{algorithm}

\end{document}

enter image description here

Tags:

Algorithms