> For the complete documentation index, see [llms.txt](https://educacion.gitbook.io/programacion/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://educacion.gitbook.io/programacion/ud2-programacion-estructurada/estructuras-repetivas/while.md).

# While

<figure><img src="/files/Ao596kbRO8BuVWNApCR3" alt=""><figcaption></figcaption></figure>

É unha estrutura de control que repite un conxunto de instrucións mentres non se cumpra unha condición. Ten as seguintes características:

* A condición avalíase **antes** de executar o bloque
* Se a condición é falsa ó inicio, o bucle non se executa nin unha vez
* Pode dar lugar a bucles infinitos se non se actualizan as variables de control

**Uso típico:** Cando non sabemos de antemano cantas veces se repetirá o proceso.

Ao igual que a sentenza `if`, `while` depende da avaliación dunha condición. O bucle `while` realiza unha nova iteración se a condición é certa.

```java
int i = 1;
while (i<3) {
    // bloque de instrucións
    System.out.println(i);
    //Modificamos a variable da condición
    i++;
}
```

## Ámbito das variables definidas no while

En Java, o ámbito das variables definidas dentro dun bucle `while` segue as mesmas regras de ámbito que outros bloques de control, como `if` ou `for`. As variables definidas dentro dun bucle `while` **teñen o seu ámbito limitado ao bloque do bucle**. Isto significa que non son accesibles fóra dese bloque.

```java
while (true) {
    int x = 10;
    System.out.println("O valor de x dentro do bucle while é: " + x);
}

System.out.println("O valor de x fóra do bucle é: " + x); // Error: non se pode atopar a variable x
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://educacion.gitbook.io/programacion/ud2-programacion-estructurada/estructuras-repetivas/while.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
