2

I want your help to write an algotihm using TeXstudio using for-loops. For the method of Gaussian elimination I have the code:

for (int i = 0; i < N-1; i++) {
   for (int j = i; j < N; j++) {
       double ratio = A[j][i]/A[i][i];
       for (int k = i; k < N; k++) {
            A[j][k] -= (ratio*A[i][k]);
            b[j] -= (ratio*b[i]);
       }
   }
}

2 Answers 2

5

One way of writing your code would be to use the listings package. Your Gaussian elimination algorithm would then be written:

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\lstset{ %
    backgroundcolor = \color{white},   % Background color
    keywordstyle    = \color{blue},    % Keyword style (just color here)
    numbers         = left,            % Add line number to the left of the code
    captionpos      = b                % Caption at the bottom of the listing
}

\begin{document}

\begin{lstlisting}[language = C, caption={Gaussian elimination algorithm}]
for (int i = 0; i < N-1; i++) {
    for (int j = i; j < N; j++) {
        double ratio = A[j][i]/A[i][i];
        for (int k = i; k < N; k++) {
            A[j][k] -= (ratio*A[i][k]);
            b[j]    -= (ratio*b[i]);
        }
    }
}
\end{lstlisting}

\end{document}

This code gives: enter image description here

If you don't want any caption for your code, just remove the caption option at the beginning of the lstlisting environment. If the language was not C, you can always change the language option to the language you are using.

4

The corresponding pseudocode; here the algorithm and algpseudocode packages are used.

\documentclass{article}

\usepackage{algorithm} % Required for pseudo code
\usepackage[noend]{algpseudocode} % Required for pseudo code

\renewcommand{\algorithmicrequire}{\textbf{Input:}} % Changes 'Require' to 'Input'

\begin{document}

\begin{algorithm}
    \caption{Caption of pseudo code}
    \begin{algorithmic}
    \Require $A$    
        \For{$i \gets 0$ to $N - 2 $}
            \For{$j \gets i$ to $N - 1 $}
                \State $ratio \gets A[j][i]/A[i][i]$
                \For{$k \gets i$ to $N - 1 $}
                    \State $A[j][k] \gets A[j][k] - (ratio*A[i][k])$
                    \State $b[j] \gets b[j] - (ratio*b[i])$
                \EndFor
            \EndFor
        \EndFor
    \end{algorithmic}
    \label{alg:code_label}
\end{algorithm}
    
\end{document}

Result: pseudo code

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.