next up previous contents index
Next: High-Level Picture Elements Up: C++ Basics Previous: Raw output   Contents   Index

Conditionals and Loops

An algorithm's behavior usually depends on some internal state. A conditional statement causes blocks of code to be executed depending on some criterion. A loop repeatedly executes a code block, usually changing the values of variables in a predictable way, so that the loop exits after finitely many traversals. Figure 2.3 illustrates both conditionals and loops with Euclid's algorithm for the greatest common divisor. Three pieces of notation require explanation: j%i means ``$ j\pmod i$'', || is logical ``or'', and == is ``test for equality''. (A single ``='' is the assignment operator.)

Figure 2.3: Euclid's division algorithm in C++.
\begin{figure}\begin{footnotesize}
\begin{verbatim}int gcd (unsigned int i, un...
... {
j=i;
i=temp;
}
return i;
}
}\end{verbatim}\end{footnotesize}\end{figure}



Andrew D. Hwang 2004-09-04