# while

> Repeats while a bool condition holds. Reach for it when the number of iterations is not known up front — otherwise a foreach or a for loop says more.

<!-- id: function-while-loop · area: function · stability: stable · html: https://osysharp.com/reference/function/while-loop/ -->

## Summary        {#summary}
`while` repeats its body as long as the condition is true, checked **before** each pass — so a condition that is false
at the start means the body never runs. The condition must be a `bool`.

## Signature      {#signature}
```osy syntax
while (<bool>) { … }
```

## Description    {#description}

### `while`, `foreach`, or `for` — which loop?   {#when}
Use `while` when you do not know up front how many passes you need — consuming until something is exhausted,
converging on a value. When you *are* walking a collection, [`foreach`](https://osysharp.com/reference/function/foreach/) says it better; when you
are counting, so does [`for`](https://osysharp.com/reference/function/for-loop/).

```osy title="halving until it fits" test app=function-while-loop
int TimesToHalve(decimal amount, decimal limit) {
  var steps = 0;
  var current = amount;
  while (current > limit) {
    current = current / 2;
    steps += 1;
  }
  return steps;
}
```

### Advance the condition, or it never ends   {#termination}
The body must move the condition towards false. A `while` whose condition never changes is an infinite loop, and the
platform will not save you from it — it will simply run until it is stopped. Make the thing the condition reads the
thing the body changes, and keep them close enough to see together.

### How do I stop part-way through?   {#leaving}
`break` leaves the loop; `continue` skips to the next check. See [break / continue](https://osysharp.com/reference/function/break-continue/).

```osy title="stopping when you have enough" test app=function-while-loop
int CountUpTo(int limit) {
  var i = 0;
  while (true) {
    i += 1;
    if (i >= limit) { break; }     // the exit is explicit, and easy to find
  }
  return i;
}
```

## See also       {#see-also}
- [foreach](https://osysharp.com/reference/function/foreach/) — walking a collection
- [for](https://osysharp.com/reference/function/for-loop/) — a counted loop
- [break / continue](https://osysharp.com/reference/function/break-continue/) — leaving a loop, or skipping a pass
