latex pseudocode code example

Example 1: latex how to write algorithm pseudocode

% in the header:
% \usepackage{algorithm}
% \usepackage{algpseudocode}

% in the  body:
\begin{algorithm}
  \caption{Euclid’s algorithm}
  \label{euclid}
  \begin{algorithmic}[1]
    \Require $x\ge5$
    \Ensure $x\le-5$
    \Function{Euclid}{$a,b$}
      \Comment{The g.c.d. of a and b}
      \State $r\gets a\bmod b$
      \While{$r \neq 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}
      \State \Return{$b$}
      \Comment{The gcd is b}
    \EndFunction
  \end{algorithmic}
\end{algorithm}

Example 2: using latex to write algorithm

\begin{program}
\mbox{A fast exponentiation procedure:}
\BEGIN \\ %
  \FOR i:=1 \TO 10 \STEP 1 \DO
     |expt|(2,i); \\ |newline|() \OD %
\rcomment{This text will be set flush to the right margin}
\WHERE
\PROC |expt|(x,n) \BODY
          z:=1;
          \DO \IF n=0 \THEN \EXIT \FI;
             \DO \IF |odd|(n) \THEN \EXIT \FI;
\COMMENT{This is a comment statement};
                n:=n/2; x:=x*x \OD;
             \{ n>0 \};
             n:=n-1; z:=z*x \OD;
          |print|(z) \ENDPROC
\END
\end{program}

Tags:

Misc Example