# Change FORALL to FOREACH in algorithms package

\FORALL gives a "for all" loop, i would like to redefine it so that it shows "for each" instead. Any way to do that?

By the way, foreach is more often used in real programming languages than forall, is that correct?

-
your second question is off topic here. Better off asking it on StackOverflow? – Seamus May 16 '11 at 10:43
I can't recall seeing a forall statement in any programming language I learned. AFAIK it would require a foreach in its implementation anyway, i.e. foreach VAR in ARRAY { if (somefunc(VAR)) { do_something } }, so it would automatically be more often used. – Martin Scharrer May 16 '11 at 11:03
@Martin: But "for all" often makes more sense in pseudocode than "for each", because pseudocode often operates on sets and it's natural to write "for all x \in Set". – Andrey Vihrov May 16 '11 at 12:19
@Andrey - I prefer "for each x in S" or more commonly "for any x in S" as "for all" indicates plural form as far as I feel. – colinfang May 16 '11 at 12:59

Simple enough and covered in the algorithms manual:

\renewcommand{\algorithmicforall}{\textbf{for each}}


This command redefines the macro that is used to typeset \FORALL. It should be placed in the document preamble.

-
Then I would also say \let\FOREACH\FORALL and use \FOREACH instead in the code. Maybe also change \FORALL to an error message afterwards. This makes the code more readable and avoids confusion. – Martin Scharrer May 16 '11 at 10:43
@Martin Is there anyway I can place \let\FOREACH\FORALL outside the begin{algorithmic} section? I tried \let\FOREACH\algorithmicforall but it didn't work – colinfang May 16 '11 at 11:41
@colinfang: I would put the \let\FOREACH\FORALL in the preamble after loading the package. Using \let\FOREACH\algorithmicforall seems to be wrong. – Martin Scharrer May 16 '11 at 11:50
@Martin - if I put it after usepackage, it doesn't work. The only way it works is to add the setting each time the environment invokes. – colinfang May 16 '11 at 12:16
@colinfang: I see, then use \def\FOREACH{\FORALL} instead. It is only a cosmetic change anyway. – Martin Scharrer May 16 '11 at 12:27

You can also use the following trick to convert \FOR into \FOREACH in algorithms package

\FOR{\textbf{each} a in b}
\STATE do something
\ENDFOR

-

There is a For Each loop in the algorithm2e package.

-
eh, I have just got used to the algorithms package... is algorithm2e better? – colinfang May 16 '11 at 10:24

The algorithmicx package lets defined its own commands. In your case you could put in the preamble:

\algblockdefx[Foreach]{Foreach}{EndForeach}[1]{\textbf{foreach} #1 \textbf{do}}{\textbf{end foreach}}


which can then be used as a For loop:

\Foreach{$i \in I$}
\State bar
\State foo
\EndForeach

-