While

While[test,body]

evaluates test, then body, repetitively, until test first fails to give True.

Details

  • While[test] does the loop with a null body.
  • If Break[] is generated in the evaluation of body, the While loop exits.
  • Continue[] exits the evaluation of body, and continues the loop.
  • Unless an explicit Return is used, the value returned by While is Null.
  • Note that in an example like i=0;While[i<0,tot+=f[i];i++] the roles of ; and , are reversed relative to C-like programming languages.

Examples

open allclose all

Basic Examples  (1)

Print and increment n while the condition n<4 is satisfied:

Scope  (2)

The body can be included as part of the test:

Break breaks out of the While:

Generalizations & Extensions  (1)

Test the condition during or at the end of the loop:

Applications  (2)

Compute the GCD of two numbers:

Count the number of iterations in a fixed-point calculation:

Properties & Relations  (4)

If the test is False, the body is never evaluated:

While returns Null:

Use Print to see the iterations:

Do iterates a fixed number of times:

NestWhile is a functional form of While:

Wolfram Research (1988), While, Wolfram Language function, https://reference.wolfram.com/language/ref/While.html.

Text

Wolfram Research (1988), While, Wolfram Language function, https://reference.wolfram.com/language/ref/While.html.

CMS

Wolfram Language. 1988. "While." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/While.html.

APA

Wolfram Language. (1988). While. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/While.html

BibTeX

@misc{reference.wolfram_2023_while, author="Wolfram Research", title="{While}", year="1988", howpublished="\url{https://reference.wolfram.com/language/ref/While.html}", note=[Accessed: 19-March-2024 ]}

BibLaTeX

@online{reference.wolfram_2023_while, organization={Wolfram Research}, title={While}, year={1988}, url={https://reference.wolfram.com/language/ref/While.html}, note=[Accessed: 19-March-2024 ]}