For in Wolfram Language

In Wolfram Language, loops are typically implemented using functional programming constructs. However, we can demonstrate similar behavior using various methods.

(* The most basic type, with a single condition *)
i = 1;
While[i <= 3,
  Print[i];
  i++
]

(* A classic initial/condition/after loop *)
Do[
  Print[j],
  {j, 0, 2}
]

(* Another way of accomplishing the basic "do this N times" iteration *)
Table[
  Print["range ", i],
  {i, 0, 2}
]

(* Infinite loop with break *)
While[True,
  Print["loop"];
  Break[]
]

(* Using continue (Skip in Wolfram Language) *)
Do[
  If[EvenQ[n],
    Continue[]
  ];
  Print[n],
  {n, 0, 5}
]

To run this code, you can copy it into a Wolfram Language notebook or use the Wolfram Engine from the command line.

Here’s an explanation of the different loop constructs:

  1. The While loop is used for the basic condition-based loop. It continues executing while the condition is true.

  2. The Do loop is used for the classic initial/condition/after loop. It’s a more concise way to iterate a specific number of times.

  3. Table is used to generate a list, but we’re using it here to iterate and print. This is similar to ranging over an integer in other languages.

  4. Another While loop is used to demonstrate an infinite loop with a Break statement. In Wolfram Language, Break[] is used to exit a loop.

  5. The last example uses Do with Continue[] (which is called Skip in Wolfram Language) to skip even numbers. EvenQ[n] checks if n is even.

Note that Wolfram Language is a functional programming language, so these imperative-style loops are not as common in idiomatic Wolfram code. Typically, you would use higher-order functions like Map, Fold, or Nest for iteration tasks.

The output of this code would be:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Wolfram Language, there are often more efficient and idiomatic ways to achieve these results using functional programming paradigms. However, these examples demonstrate how traditional loop constructs can be approximated in Wolfram Language.