En este tutorial, aprenderemos el uso de while y do… while en la programación de C ++ con la ayuda de algunos ejemplos.
En programación de computadoras, los bucles se utilizan para repetir un bloque de código.
Por ejemplo, digamos que queremos mostrar un mensaje 100 veces. Entonces, en lugar de escribir la declaración de impresión 100 veces, podemos usar un ciclo.
Ese fue solo un ejemplo simple; podemos lograr mucha más eficiencia y sofisticación en nuestros programas haciendo un uso efectivo de los bucles.
Hay 3 tipos de bucles en C ++.
for
lazowhile
lazodo… while
lazo
En el tutorial anterior, aprendimos sobre el ciclo for de C ++. Aquí, vamos a aprender sobre while
y do… while
bucles.
C ++ while Loop
La sintaxis del while
bucle es:
while (condition) ( // body of the loop )
Aquí,
- Un
while
bucle evalúa elcondition
- Si se
condition
evalúa entrue
,while
se ejecuta el código dentro del ciclo. - Se
condition
evalúa de nuevo. - Este proceso continúa hasta que
condition
esfalse
. - Cuando se
condition
evalúa enfalse
, el ciclo termina.
Para obtener más información sobre conditions
, visite Operadores lógicos y relacionales de C ++.
Diagrama de flujo de while Loop

Ejemplo 1: Mostrar números del 1 al 5
// C++ Program to print numbers from 1 to 5 #include using namespace std; int main() ( int i = 1; // while loop from 1 to 5 while (i <= 5) ( cout << i << " "; ++i; ) return 0; )
Salida
1 2 3 4 5
Así es como funciona el programa.
Iteración | Variable | yo <= 5 | Acción |
---|---|---|---|
Primero | i = 1 | true | 1 se imprime y i aumenta a 2 . |
2do | i = 2 | true | 2 se imprime y i aumenta a 3 . |
Tercero | i = 3 | true | 3 se imprime y i aumenta a4 |
Cuarto | i = 4 | true | 4 se imprime y i aumenta a 5 . |
Quinto | i = 5 | true | 5 se imprime y i aumenta a 6 . |
Sexto | i = 6 | false | El bucle se termina |
Ejemplo 2: Suma de números positivos únicamente
// program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include using namespace std; int main() ( int number; int sum = 0; // take input from the user cout <> number; while (number>= 0) ( // add all positive numbers sum += number; // take input again if the number is positive cout <> number; ) // display the sum cout << "The sum is " << sum << endl; return 0; )
Salida
Ingrese un número: 6 Ingrese un número: 12 Ingrese un número: 7 Ingrese un número: 0 Ingrese un número: -2 La suma es 25
En este programa, se solicita al usuario que ingrese un número, que se almacena en el número de variable.
Para almacenar la suma de los números, declaramos una variable suma y la inicializamos con el valor de 0
.
El while
ciclo continúa hasta que el usuario ingresa un número negativo. Durante cada iteración, el número ingresado por el usuario se agrega a la variable de suma.
Cuando el usuario ingresa un número negativo, el ciclo termina. Finalmente, se muestra la suma total.
C ++ hacer … while Loop
El do… while
bucle es una variante del while
bucle con una diferencia importante: el cuerpo del do… while
bucle se ejecuta una vez antes de condition
comprobarlo.
Su sintaxis es:
do ( // body of loop; ) while (condition);
Aquí,
- El cuerpo del bucle se ejecuta al principio. Luego
condition
se evalúa. - Si se
condition
evalúa entrue
, el cuerpo del bucle dentro de lado
declaración se ejecuta nuevamente. - Se
condition
evalúa una vez más. - Si se
condition
evalúa entrue
, el cuerpo del bucle dentro de lado
declaración se ejecuta nuevamente. - Este proceso continúa hasta que se
condition
evalúa afalse
. Entonces el bucle se detiene.
Diagrama de flujo de do… while Loop

Ejemplo 3: Mostrar números del 1 al 5
// C++ Program to print numbers from 1 to 5 #include using namespace std; int main() ( int i = 1; // do… while loop from 1 to 5 do ( cout << i << " "; ++i; ) while (i <= 5); return 0; )
Salida
1 2 3 4 5
Así es como funciona el programa.
Iteración | Variable | yo <= 5 | Acción |
---|---|---|---|
i = 1 | Sin revisar | Se imprime 1 y i se aumenta a 2 |
|
Primero | i = 2 | true | 2 se imprime y i aumenta a 3 |
2do | i = 3 | true | Se imprime 3 y i se aumenta a 4 |
Tercero | i = 4 | true | Se imprime 4 y i se aumenta a 5 |
Cuarto | i = 5 | true | Se imprime 5 y i se aumenta a 6 |
Quinto | i = 6 | false | El bucle se termina |
Ejemplo 4: Suma de números positivos únicamente
// program to find the sum of positive numbers // If the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include using namespace std; int main() ( int number = 0; int sum = 0; do ( sum += number; // take input from the user cout <> number; ) while (number>= 0); // display the sum cout << "The sum is " << sum << endl; return 0; )
Salida 1
Ingrese un número: 6 Ingrese un número: 12 Ingrese un número: 7 Ingrese un número: 0 Ingrese un número: -2 La suma es 25
Here, the do… while
loop continues until the user enters a negative number. When the number is negative, the loop terminates; the negative number is not added to the sum
variable.
Output 2
Enter a number: -6 The sum is 0.
The body of the do… while
loop runs only once if the user enters a negative number.
Infinite while loop
If the condition
of a loop is always true
, the loop runs for infinite times (until the memory is full). For example,
// infinite while loop while(true) ( // body of the loop )
Here is an example of an infinite do… while
loop.
// infinite do… while loop int count = 1; do ( // body of loop ) while(count == 1);
In the above programs, the condition
is always true
. Hence, the loop body will run for infinite times.
for vs while loops
A for
loop is usually used when the number of iterations is known. For example,
// This loop is iterated 5 times for (int i = 1; i <=5; ++i) ( // body of the loop )
Here, we know that the for-loop will be executed 5 times.
Sin embargo, los bucles while
y do… while
se suelen utilizar cuando se desconoce el número de iteraciones. Por ejemplo,
while (condition) ( // body of the loop )
Consulte estos ejemplos para obtener más información:
- Programa C ++ para mostrar la serie Fibonacci
- Programa C ++ para encontrar GCD
- Programa C ++ para encontrar LCM