C ++ while y do ... while Loop (con ejemplos)

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 ++.

  1. for lazo
  2. while lazo
  3. do… while lazo

En el tutorial anterior, aprendimos sobre el ciclo for de C ++. Aquí, vamos a aprender sobre whiley do… whilebucles.

C ++ while Loop

La sintaxis del whilebucle es:

 while (condition) ( // body of the loop )

Aquí,

  • Un whilebucle evalúa elcondition
  • Si se conditionevalúa en true, whilese ejecuta el código dentro del ciclo.
  • Se conditionevalúa de nuevo.
  • Este proceso continúa hasta que conditiones false.
  • Cuando se conditionevalúa en false, 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

Diagrama de flujo de C ++ 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 iaumenta a 2.
2do i = 2 true 2 se imprime y iaumenta a 3.
Tercero i = 3 true 3 se imprime y iaumenta a4
Cuarto i = 4 true 4 se imprime y iaumenta a 5.
Quinto i = 5 true 5 se imprime y iaumenta 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 whileciclo 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… whilebucle es una variante del whilebucle con una diferencia importante: el cuerpo del do… whilebucle se ejecuta una vez antes de conditioncomprobarlo.

Su sintaxis es:

 do ( // body of loop; ) while (condition);

Aquí,

  • El cuerpo del bucle se ejecuta al principio. Luego conditionse evalúa.
  • Si se conditionevalúa en true, el cuerpo del bucle dentro de la dodeclaración se ejecuta nuevamente.
  • Se conditionevalúa una vez más.
  • Si se conditionevalúa en true, el cuerpo del bucle dentro de la dodeclaración se ejecuta nuevamente.
  • Este proceso continúa hasta que se conditionevalúa a false. Entonces el bucle se detiene.

Diagrama de flujo de do… while Loop

Diagrama de flujo de C ++ 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 ise aumenta a 2
Primero i = 2 true 2 se imprime y iaumenta a 3
2do i = 3 true Se imprime 3 y ise aumenta a 4
Tercero i = 4 true Se imprime 4 y ise aumenta a 5
Cuarto i = 5 true Se imprime 5 y ise 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 whiley do… whilese 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

Articulos interesantes...