Skip to content
Snippets Groups Projects
Commit d450c057 authored by Stéphane Del Pino's avatar Stéphane Del Pino
Browse files

Describe for loops

parent ceee5ebb
No related branches found
No related tags found
1 merge request!145git subrepo clone git@gitlab.com:OlMon/org-themes.git packages/org-themes
......@@ -1878,7 +1878,65 @@ We give a final illustration
#+END_SRC
#+results: if-block
*** TODO for loops
*** ~for~ loops
~pugs~ allow to write ~for~ loops. It follows the ~C++~ syntax
#+BEGIN_SRC pugs :exports code
for (declarationinstruction ; condition ; postinstruction) statement
#+END_SRC
Following ~C++~, ~declarationinstruction~, ~condition~ and ~postinstruction~
are optional. The ~condition~ argument if present *must* be a boolean
value (type ~B~), if it is absent, the default value ~true~ is used.
- The ~declarationinstruction~ is execute only *once* /before/ the beginning
of the loop. The lifetime of the variable declared here is defined
by the ~for~ instruction itself.
- The ~condition~ is evaluate /before/ each loop.
- The ~postinstruction~ is executed /after/ each loop.
- The ~statement~ is either a single instruction or a block of
instructions. The ~statement~ is executed if the ~condition~ has the
value ~true~.
For instance, one can write
#+NAME: for-block
#+BEGIN_SRC pugs :exports both :results output
let n:N, n = 10;
let sum:N, sum = 0;
for (let i:N, i=1; i<=n; ++i) {
sum += i;
}
cout << "sum = " << sum << "\n";
#+END_SRC
which gives as expected
#+results: for-block
The lifetime of the declared variable (in the ~declarationinstruction~
statement) is illustrate by the following example
#+NAME: for-scope-error
#+BEGIN_SRC pugs-error :exports both :results output
for (let i:N, i=0; i<2; ++i) {
cout << "i = " << i << "\n";
}
cout << "i = " << i << "\n";
#+END_SRC
Running this example produces the following error
#+results: for-scope-error
To fix the previous code, one can write
#+NAME: for-no-decl
#+BEGIN_SRC pugs :exports both :results output
let i:N, i=0;
for (; i<2; ++i) {
cout << "i = " << i << "\n";
}
cout << "i = " << i << "\n";
#+END_SRC
One gets
#+results: for-no-decl
*** TODO do while loops
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment