logo

hacer mientras bucle en C

A bucle es una estructura de control de programación que le permite ejecutar una bloque de código indefinidamente si se cumple una condición específica. Los bucles se utilizan para ejecutar actividades repetitivas y mejorar el rendimiento de la programación. Hay múltiples bucles en el lenguaje de programación C, uno de los cuales es el bucle 'hacer-mientras' .

A bucle 'hacer-mientras' es una forma de un bucle en C que ejecuta primero el bloque de código, seguido de la condición. Si la condición es verdadero , el bucle continúa corriendo; de lo contrario, se detiene. Sin embargo, si la condición es originalmente verdadero , garantiza que el bloque de código se realice al menos una vez.

hacer mientras la sintaxis del bucle

La sintaxis del bucle do- while del lenguaje C se proporciona a continuación:

 do{ //code to be executed }while(condition); 

Los componentes se dividen en lo siguiente:

cómo desactivar el modo desarrollador de Android
  • El hacer palabra clave marca el comienzo del bucle.
  • El bloque de código dentro llaves {} es el cuerpo del bucle, que contiene el código que desea repetir.
  • El mientras palabra clave va seguido de una condición entre paréntesis (). Una vez ejecutado el bloque de código, se verifica esta condición. Si la condición es verdadero , el bucle continúa en lo demás, el extremos del bucle .

Trabajo de do while Loop en C

Veamos un ejemplo de cómo un bucle hacer-mientras funciona en C. En este ejemplo, escribiremos un programa simple que pregunta al usuario por una contraseña y sigue preguntando hasta que se ingresa la contraseña correcta.

Ejemplo:

 #include #include int main() { char password[] = 'secret'; char input[20]; do { printf('Enter the password: '); scanf('%s', input); } while (strcmp(input, password) != 0); printf('Access granted!
'); return 0; } 

El programa se ejecuta de la siguiente manera:

  1. Se incluyen los siguientes archivos de encabezado: para estándar aporte y producción rutinas y para cuerda funciones de manipulación .
  2. La contraseña correcta se define como matriz de caracteres (contraseña de caracteres []) con el valor 'secreto'
  3. Después de eso, definimos otra entrada de matriz de caracteres para almacenar la entrada del usuario.
  4. El hacer palabra clave indica que el bloque de código incluido dentro del bucle se realizará al menos una vez.
  5. Utilizando el función printf() , mostramos un mensaje solicitando al usuario que ingrese su contraseña dentro del Loop.
  6. A continuación leemos el entrada del usuario utilizando el función scanf() y guardarlo en el matriz de entrada .
  7. Después de leer el aporte , utilizamos el función strcmp() para comparar la entrada con la contraseña correcta. Si las cuerdas son igual, el función strcmp devuelve 0. Entonces, continuamos haciendo el bucle siempre que la entrada y la contraseña no sean iguales.
  8. Una vez el contraseña correcta se ingresa, el ciclo termina e imprimimos '¡Acceso permitido!' utilizando el función printf() .
  9. Después de eso, el programa devuelve 0 para indicar una ejecución exitosa.

Producción:

Analicemos un posible escenario:

 Enter the password: 123 Enter the password: abc Enter the password: secret Access Granted! 

Explicación:

En este ejemplo, el usuario ingresa inicialmente contraseñas incorrectas, '123' y 'a B C' . El bucle solicita al usuario hasta que ingresa la contraseña correcta. 'secreto' es ingresado. Una vez que se proporciona la contraseña correcta, el ciclo finaliza y el '¡Acceso permitido!' Se muestra el mensaje.

Ejemplo de bucle do while en C:

Ejemplo 1:

He aquí un ejemplo sencillo de un bucle 'hacer-mientras' en C que imprime números del 1 al 5:

 #include int main() { inti = 1; do { printf('%d
&apos;, i); i++; } while (i<= 5); return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> 1 2 3 4 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, the <strong> <em>code block</em> </strong> within the do loop will be executed at least once, printing numbers from <strong> <em>1 to 5</em> </strong> . After each iteration, the <strong> <em>i value</em> </strong> is incremented, and the condition <strong> <em>i<= 5< em> </=></em></strong> is checked. If the condition is still true, the loop continues; otherwise, it terminates.</p> <p> <strong>Example 2:</strong> </p> <p>Program to print table for the given number using do while Loop</p> <pre> #include intmain(){ inti=1,number=0; printf(&apos;Enter a number: &apos;); scanf(&apos;%d&apos;,&amp;number); do{ printf(&apos;%d 
&apos;,(number*i)); i++; }while(i<=10); return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Enter a number: 5 5 10 15 20 25 30 35 40 45 50 Enter a number: 10 10 20 30 40 50 60 70 80 90 100 </pre> <p> <strong>Example 3:</strong> </p> <p>Let&apos;s take a program that prints the multiplication table of a given number N using a <strong> <em>do...while Loop</em> :</strong> </p> <pre> #include int main() { int N; printf(&apos;Enter a number to generate its multiplication table: &apos;); scanf(&apos;%d&apos;, &amp;N); inti = 1; do { printf(&apos;%d x %d = %d
&apos;, N, i, N * i); i++; } while (i<= 10); return 0; } < pre> <p> <strong>Output:</strong> </p> <p>Let us say you enter the number 7 as input:</p> <pre> Please enter a number to generate its multiplication table: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 </pre> <p>The program calculates and prints the multiplication table for <strong> <em>7</em> </strong> from 1 to 10.</p> <h3>Infinite do while loop</h3> <p>An <strong> <em>infinite loop</em> </strong> is a loop that runs indefinitely as its condition is always <strong> <em>true</em> </strong> or it lacks a terminating condition. Here is an example of an <strong> <em>infinite do...while loop</em> </strong> in C:</p> <p> <strong>Example:</strong> </p> <pre> #include int main() { inti = 1; do { printf(&apos;Iteration %d
&apos;, i); i++; } while (1); // Condition is always true return 0; } </pre> <p>In this <strong> <em>example</em> </strong> , the <strong> <em>loop</em> </strong> will keep running <strong> <em>indefinitely</em> </strong> because <strong> <em>condition 1</em> </strong> is always <strong> <em>true</em> </strong> .</p> <p> <strong>Output:</strong> </p> <p>When you run the program, you will see that it continues printing <strong> <em>&apos;Iteration x&apos;,</em> </strong> where x is the <strong> <em>iteration number</em> </strong> without stopping:</p> <pre> Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 ... (and so on) </pre> <p>To interrupt an infinite loop like this, you generally use a <strong> <em>break statement</em> </strong> within the <strong> <em>loop</em> </strong> or some external condition you can control, such as <strong> <em>hitting</em> </strong> a specific key combination. In most desktop settings, the keyboard shortcut <strong> <em>Ctrl+C</em> </strong> can escape the Loop.</p> <h3>Nested do while loop in C</h3> <p>In C, we take an example of a <strong> <em>nested do...while loop</em> </strong> . In this example, we will write a program that uses <strong> <em>nested do...while loops</em> </strong> to create a numerical pattern.</p> <p> <strong>Example:</strong> </p> <pre> #include int main() { int rows, i = 1; printf(&apos;Enter the number of rows: &apos;); scanf(&apos;%d&apos;, &amp;rows); do { int j = 1; do { printf(&apos;%d &apos;, j); j++; } while (j <= i); printf('
'); i++; } while (i<="rows);" return 0; < pre> <p>In this program, we use <strong> <em>nested do...while loops</em> </strong> to generate a pattern of numbers. The <strong> <em>outer loop</em> </strong> controls the number of rows, and the <strong> <em>inner loop</em> </strong> generates the numbers for each row.</p> <p> <strong>Output:</strong> </p> <p>Let us say you input five as the number of rows:</p> <pre> Enter the number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, the program generates a pattern of numbers in a <strong> <em>triangular shape</em> </strong> . The <strong> <em>outer loop</em> </strong> iterates over the rows, and the <strong> <em>inner loop</em> </strong> iterates within each row, printing the numbers from 1 up to the current row number.</p> <h2>Difference between while and do while Loop</h2> <p>Here is a tabular comparison between the while loop and the do-while Loop in C:</p> <table class="table"> <tr> <th>Aspect</th> <th>while loop</th> <th>do-while loop</th> </tr> <tr> <td> <strong>Syntax</strong> </td> <td>while (condition) { ... }</td> <td>do { ... } while (condition);</td> </tr> <tr> <td> <strong>Loop Body Execution</strong> </td> <td>Condition is checked before execution.</td> <td>The body is executed before the condition.</td> </tr> <tr> <td> <strong>First Execution</strong> </td> <td>The condition must be true initially.</td> <td>The body is executed at least once.</td> </tr> <tr> <td> <strong>Loop Execution</strong> </td> <td>May execute zero or more times.</td> <td>Will execute at least once.</td> </tr> <tr> <td> <strong>Example</strong> </td> <td>while (i<5) { printf('%d
', i); i++; }< td> <td>do { printf(&apos;%d
&apos;, i); i++; } while (i<5);< td> </5);<></td></5)></td></tr> <tr> <td> <strong>Common Use Cases</strong> </td> <td>When the loop may not run at all.</td> <td>When you want the loop to run at least once.</td> </tr> </table> <p> <strong>While Loop:</strong> The loop body is executed before the condition is checked. If the condition is initially <strong> <em>false</em> </strong> , the loop may not execute.</p> <p> <strong>Do-while Loop:</strong> The <strong> <em>loop body</em> </strong> is executed at least once before the condition is <strong> <em>checked</em> </strong> . This guarantees that the loop completes at least one iteration.</p> <p>When you want the <strong> <em>loop</em> </strong> to run based on a condition that may be <strong> <em>false</em> </strong> at first, use the <strong> <em>while loop</em> </strong> , and when you want the loop to run at least once regardless of the starting state, use the <strong> <em>do-while loop.</em> </strong> </p> <h2>Features of do while loop</h2> <p>The do-while loop in C has several fundamental characteristics that make it an effective programming technique in certain situations. The following are the significant characteristics of the do-while loop:</p> <ul> <tr><td>Guaranteed Execution:</td> Unlike other <strong> <em>loop structures</em> </strong> , the <strong> <em>do-while oop</em> </strong> ensures that the loop body is executed at least once. Because the condition is assessed after the loop body, the code within the loop is performed before the condition is verified. </tr><tr><td>Loop after testing:</td> The <strong> <em>do-while loop</em> </strong> is a post-tested loop which implies that the loop condition is assessed after the loop body has been executed. If the condition is true, the loop body is run once again. This behavior allows you to verify the condition for repetition before ensuring that a given activity is completed. </tr><tr><td>Conditionally Controlled:</td> The loop continues to execute as long as the condition specified after the while keyword remains <strong> <em>true</em> </strong> . When the condition evaluates to <strong> <em>false</em> </strong> , the loop is terminated, and control shifts to the sentence after the loop. </tr><tr><td>Flexibility:</td> The <strong> <em>do-while loop</em> </strong> may be utilized in several contexts. It is typically used in cases where a piece of code must be executed at least once, such as <strong> <em>menu-driven programs, input validation,</em> </strong> or <strong> <em>repetitive computations</em> </strong> . </tr><tr><td>Nesting Capability:</td> Similar to other <strong> <em>loop constructs</em> </strong> , the <strong> <em>do-while loop</em> </strong> can be <strong> <em>nested</em> </strong> inside other <strong> <em>loops</em> </strong> or <strong> <em>control structures</em> </strong> to create more complex control flow patterns. It allows for the creation of <strong> <em>nested loops</em> </strong> and the implementation of intricate repetitive tasks. </tr><tr><td>Break and Continue:</td> The break statement can be used within a <strong> <em>do-while loop</em> </strong> to terminate the loop execution and exit the loop prematurely. The <strong> <em>continue statement</em> </strong> can skip the remaining code in the current iteration and jump to the next iteration of the loop. </tr><tr><td>Local Scope:</td> Variables declared inside the <strong> <em>do-while loop</em> </strong> body have local scope and are accessible only within the <strong> <em>loop block.</em> </strong> They cannot be accessed outside the loop or by other loops or control structures. </tr><tr><td>Infinite Loop Control:</td> It is crucial to ensure that the loop&apos;s condition is eventually modified within the <strong> <em>loop body</em> </strong> . This modification is necessary to prevent infinite loops where the condition continually evaluates to true. Modifying the condition ensures that the loop terminates at some point. </tr></ul> <hr></=></pre></=></pre></=10);></pre></=>

Explicación:

En este ejemplo, el bloque de código dentro del bucle do se ejecutará al menos una vez, imprimiendo números de 1 a 5 . Después de cada iteración, el yo valoro se incrementa y la condición i<= 5< em> está chequeado. Si la condición sigue siendo verdadera, el ciclo continúa; de lo contrario, termina.

Ejemplo 2:

Programa para imprimir la tabla para el número dado usando do while Loop

 #include intmain(){ inti=1,number=0; printf(&apos;Enter a number: &apos;); scanf(&apos;%d&apos;,&amp;number); do{ printf(&apos;%d 
&apos;,(number*i)); i++; }while(i<=10); return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Enter a number: 5 5 10 15 20 25 30 35 40 45 50 Enter a number: 10 10 20 30 40 50 60 70 80 90 100 </pre> <p> <strong>Example 3:</strong> </p> <p>Let&apos;s take a program that prints the multiplication table of a given number N using a <strong> <em>do...while Loop</em> :</strong> </p> <pre> #include int main() { int N; printf(&apos;Enter a number to generate its multiplication table: &apos;); scanf(&apos;%d&apos;, &amp;N); inti = 1; do { printf(&apos;%d x %d = %d
&apos;, N, i, N * i); i++; } while (i<= 10); return 0; } < pre> <p> <strong>Output:</strong> </p> <p>Let us say you enter the number 7 as input:</p> <pre> Please enter a number to generate its multiplication table: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 </pre> <p>The program calculates and prints the multiplication table for <strong> <em>7</em> </strong> from 1 to 10.</p> <h3>Infinite do while loop</h3> <p>An <strong> <em>infinite loop</em> </strong> is a loop that runs indefinitely as its condition is always <strong> <em>true</em> </strong> or it lacks a terminating condition. Here is an example of an <strong> <em>infinite do...while loop</em> </strong> in C:</p> <p> <strong>Example:</strong> </p> <pre> #include int main() { inti = 1; do { printf(&apos;Iteration %d
&apos;, i); i++; } while (1); // Condition is always true return 0; } </pre> <p>In this <strong> <em>example</em> </strong> , the <strong> <em>loop</em> </strong> will keep running <strong> <em>indefinitely</em> </strong> because <strong> <em>condition 1</em> </strong> is always <strong> <em>true</em> </strong> .</p> <p> <strong>Output:</strong> </p> <p>When you run the program, you will see that it continues printing <strong> <em>&apos;Iteration x&apos;,</em> </strong> where x is the <strong> <em>iteration number</em> </strong> without stopping:</p> <pre> Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 ... (and so on) </pre> <p>To interrupt an infinite loop like this, you generally use a <strong> <em>break statement</em> </strong> within the <strong> <em>loop</em> </strong> or some external condition you can control, such as <strong> <em>hitting</em> </strong> a specific key combination. In most desktop settings, the keyboard shortcut <strong> <em>Ctrl+C</em> </strong> can escape the Loop.</p> <h3>Nested do while loop in C</h3> <p>In C, we take an example of a <strong> <em>nested do...while loop</em> </strong> . In this example, we will write a program that uses <strong> <em>nested do...while loops</em> </strong> to create a numerical pattern.</p> <p> <strong>Example:</strong> </p> <pre> #include int main() { int rows, i = 1; printf(&apos;Enter the number of rows: &apos;); scanf(&apos;%d&apos;, &amp;rows); do { int j = 1; do { printf(&apos;%d &apos;, j); j++; } while (j <= i); printf(\'
\'); i++; } while (i<="rows);" return 0; < pre> <p>In this program, we use <strong> <em>nested do...while loops</em> </strong> to generate a pattern of numbers. The <strong> <em>outer loop</em> </strong> controls the number of rows, and the <strong> <em>inner loop</em> </strong> generates the numbers for each row.</p> <p> <strong>Output:</strong> </p> <p>Let us say you input five as the number of rows:</p> <pre> Enter the number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, the program generates a pattern of numbers in a <strong> <em>triangular shape</em> </strong> . The <strong> <em>outer loop</em> </strong> iterates over the rows, and the <strong> <em>inner loop</em> </strong> iterates within each row, printing the numbers from 1 up to the current row number.</p> <h2>Difference between while and do while Loop</h2> <p>Here is a tabular comparison between the while loop and the do-while Loop in C:</p> <table class="table"> <tr> <th>Aspect</th> <th>while loop</th> <th>do-while loop</th> </tr> <tr> <td> <strong>Syntax</strong> </td> <td>while (condition) { ... }</td> <td>do { ... } while (condition);</td> </tr> <tr> <td> <strong>Loop Body Execution</strong> </td> <td>Condition is checked before execution.</td> <td>The body is executed before the condition.</td> </tr> <tr> <td> <strong>First Execution</strong> </td> <td>The condition must be true initially.</td> <td>The body is executed at least once.</td> </tr> <tr> <td> <strong>Loop Execution</strong> </td> <td>May execute zero or more times.</td> <td>Will execute at least once.</td> </tr> <tr> <td> <strong>Example</strong> </td> <td>while (i<5) { printf(\'%d
\', i); i++; }< td> <td>do { printf(&apos;%d
&apos;, i); i++; } while (i<5);< td> </5);<></td></5)></td></tr> <tr> <td> <strong>Common Use Cases</strong> </td> <td>When the loop may not run at all.</td> <td>When you want the loop to run at least once.</td> </tr> </table> <p> <strong>While Loop:</strong> The loop body is executed before the condition is checked. If the condition is initially <strong> <em>false</em> </strong> , the loop may not execute.</p> <p> <strong>Do-while Loop:</strong> The <strong> <em>loop body</em> </strong> is executed at least once before the condition is <strong> <em>checked</em> </strong> . This guarantees that the loop completes at least one iteration.</p> <p>When you want the <strong> <em>loop</em> </strong> to run based on a condition that may be <strong> <em>false</em> </strong> at first, use the <strong> <em>while loop</em> </strong> , and when you want the loop to run at least once regardless of the starting state, use the <strong> <em>do-while loop.</em> </strong> </p> <h2>Features of do while loop</h2> <p>The do-while loop in C has several fundamental characteristics that make it an effective programming technique in certain situations. The following are the significant characteristics of the do-while loop:</p> <ul> <tr><td>Guaranteed Execution:</td> Unlike other <strong> <em>loop structures</em> </strong> , the <strong> <em>do-while oop</em> </strong> ensures that the loop body is executed at least once. Because the condition is assessed after the loop body, the code within the loop is performed before the condition is verified. </tr><tr><td>Loop after testing:</td> The <strong> <em>do-while loop</em> </strong> is a post-tested loop which implies that the loop condition is assessed after the loop body has been executed. If the condition is true, the loop body is run once again. This behavior allows you to verify the condition for repetition before ensuring that a given activity is completed. </tr><tr><td>Conditionally Controlled:</td> The loop continues to execute as long as the condition specified after the while keyword remains <strong> <em>true</em> </strong> . When the condition evaluates to <strong> <em>false</em> </strong> , the loop is terminated, and control shifts to the sentence after the loop. </tr><tr><td>Flexibility:</td> The <strong> <em>do-while loop</em> </strong> may be utilized in several contexts. It is typically used in cases where a piece of code must be executed at least once, such as <strong> <em>menu-driven programs, input validation,</em> </strong> or <strong> <em>repetitive computations</em> </strong> . </tr><tr><td>Nesting Capability:</td> Similar to other <strong> <em>loop constructs</em> </strong> , the <strong> <em>do-while loop</em> </strong> can be <strong> <em>nested</em> </strong> inside other <strong> <em>loops</em> </strong> or <strong> <em>control structures</em> </strong> to create more complex control flow patterns. It allows for the creation of <strong> <em>nested loops</em> </strong> and the implementation of intricate repetitive tasks. </tr><tr><td>Break and Continue:</td> The break statement can be used within a <strong> <em>do-while loop</em> </strong> to terminate the loop execution and exit the loop prematurely. The <strong> <em>continue statement</em> </strong> can skip the remaining code in the current iteration and jump to the next iteration of the loop. </tr><tr><td>Local Scope:</td> Variables declared inside the <strong> <em>do-while loop</em> </strong> body have local scope and are accessible only within the <strong> <em>loop block.</em> </strong> They cannot be accessed outside the loop or by other loops or control structures. </tr><tr><td>Infinite Loop Control:</td> It is crucial to ensure that the loop&apos;s condition is eventually modified within the <strong> <em>loop body</em> </strong> . This modification is necessary to prevent infinite loops where the condition continually evaluates to true. Modifying the condition ensures that the loop terminates at some point. </tr></ul> <hr></=></pre></=></pre></=10);>

Ejemplo 3:

Tomemos un programa que imprime la tabla de multiplicar de un número dado N usando un hacer...mientras bucle :

 #include int main() { int N; printf(&apos;Enter a number to generate its multiplication table: &apos;); scanf(&apos;%d&apos;, &amp;N); inti = 1; do { printf(&apos;%d x %d = %d
&apos;, N, i, N * i); i++; } while (i<= 10); return 0; } < pre> <p> <strong>Output:</strong> </p> <p>Let us say you enter the number 7 as input:</p> <pre> Please enter a number to generate its multiplication table: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 </pre> <p>The program calculates and prints the multiplication table for <strong> <em>7</em> </strong> from 1 to 10.</p> <h3>Infinite do while loop</h3> <p>An <strong> <em>infinite loop</em> </strong> is a loop that runs indefinitely as its condition is always <strong> <em>true</em> </strong> or it lacks a terminating condition. Here is an example of an <strong> <em>infinite do...while loop</em> </strong> in C:</p> <p> <strong>Example:</strong> </p> <pre> #include int main() { inti = 1; do { printf(&apos;Iteration %d
&apos;, i); i++; } while (1); // Condition is always true return 0; } </pre> <p>In this <strong> <em>example</em> </strong> , the <strong> <em>loop</em> </strong> will keep running <strong> <em>indefinitely</em> </strong> because <strong> <em>condition 1</em> </strong> is always <strong> <em>true</em> </strong> .</p> <p> <strong>Output:</strong> </p> <p>When you run the program, you will see that it continues printing <strong> <em>&apos;Iteration x&apos;,</em> </strong> where x is the <strong> <em>iteration number</em> </strong> without stopping:</p> <pre> Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 ... (and so on) </pre> <p>To interrupt an infinite loop like this, you generally use a <strong> <em>break statement</em> </strong> within the <strong> <em>loop</em> </strong> or some external condition you can control, such as <strong> <em>hitting</em> </strong> a specific key combination. In most desktop settings, the keyboard shortcut <strong> <em>Ctrl+C</em> </strong> can escape the Loop.</p> <h3>Nested do while loop in C</h3> <p>In C, we take an example of a <strong> <em>nested do...while loop</em> </strong> . In this example, we will write a program that uses <strong> <em>nested do...while loops</em> </strong> to create a numerical pattern.</p> <p> <strong>Example:</strong> </p> <pre> #include int main() { int rows, i = 1; printf(&apos;Enter the number of rows: &apos;); scanf(&apos;%d&apos;, &amp;rows); do { int j = 1; do { printf(&apos;%d &apos;, j); j++; } while (j <= i); printf(\'
\'); i++; } while (i<="rows);" return 0; < pre> <p>In this program, we use <strong> <em>nested do...while loops</em> </strong> to generate a pattern of numbers. The <strong> <em>outer loop</em> </strong> controls the number of rows, and the <strong> <em>inner loop</em> </strong> generates the numbers for each row.</p> <p> <strong>Output:</strong> </p> <p>Let us say you input five as the number of rows:</p> <pre> Enter the number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, the program generates a pattern of numbers in a <strong> <em>triangular shape</em> </strong> . The <strong> <em>outer loop</em> </strong> iterates over the rows, and the <strong> <em>inner loop</em> </strong> iterates within each row, printing the numbers from 1 up to the current row number.</p> <h2>Difference between while and do while Loop</h2> <p>Here is a tabular comparison between the while loop and the do-while Loop in C:</p> <table class="table"> <tr> <th>Aspect</th> <th>while loop</th> <th>do-while loop</th> </tr> <tr> <td> <strong>Syntax</strong> </td> <td>while (condition) { ... }</td> <td>do { ... } while (condition);</td> </tr> <tr> <td> <strong>Loop Body Execution</strong> </td> <td>Condition is checked before execution.</td> <td>The body is executed before the condition.</td> </tr> <tr> <td> <strong>First Execution</strong> </td> <td>The condition must be true initially.</td> <td>The body is executed at least once.</td> </tr> <tr> <td> <strong>Loop Execution</strong> </td> <td>May execute zero or more times.</td> <td>Will execute at least once.</td> </tr> <tr> <td> <strong>Example</strong> </td> <td>while (i<5) { printf(\'%d
\', i); i++; }< td> <td>do { printf(&apos;%d
&apos;, i); i++; } while (i<5);< td> </5);<></td></5)></td></tr> <tr> <td> <strong>Common Use Cases</strong> </td> <td>When the loop may not run at all.</td> <td>When you want the loop to run at least once.</td> </tr> </table> <p> <strong>While Loop:</strong> The loop body is executed before the condition is checked. If the condition is initially <strong> <em>false</em> </strong> , the loop may not execute.</p> <p> <strong>Do-while Loop:</strong> The <strong> <em>loop body</em> </strong> is executed at least once before the condition is <strong> <em>checked</em> </strong> . This guarantees that the loop completes at least one iteration.</p> <p>When you want the <strong> <em>loop</em> </strong> to run based on a condition that may be <strong> <em>false</em> </strong> at first, use the <strong> <em>while loop</em> </strong> , and when you want the loop to run at least once regardless of the starting state, use the <strong> <em>do-while loop.</em> </strong> </p> <h2>Features of do while loop</h2> <p>The do-while loop in C has several fundamental characteristics that make it an effective programming technique in certain situations. The following are the significant characteristics of the do-while loop:</p> <ul> <tr><td>Guaranteed Execution:</td> Unlike other <strong> <em>loop structures</em> </strong> , the <strong> <em>do-while oop</em> </strong> ensures that the loop body is executed at least once. Because the condition is assessed after the loop body, the code within the loop is performed before the condition is verified. </tr><tr><td>Loop after testing:</td> The <strong> <em>do-while loop</em> </strong> is a post-tested loop which implies that the loop condition is assessed after the loop body has been executed. If the condition is true, the loop body is run once again. This behavior allows you to verify the condition for repetition before ensuring that a given activity is completed. </tr><tr><td>Conditionally Controlled:</td> The loop continues to execute as long as the condition specified after the while keyword remains <strong> <em>true</em> </strong> . When the condition evaluates to <strong> <em>false</em> </strong> , the loop is terminated, and control shifts to the sentence after the loop. </tr><tr><td>Flexibility:</td> The <strong> <em>do-while loop</em> </strong> may be utilized in several contexts. It is typically used in cases where a piece of code must be executed at least once, such as <strong> <em>menu-driven programs, input validation,</em> </strong> or <strong> <em>repetitive computations</em> </strong> . </tr><tr><td>Nesting Capability:</td> Similar to other <strong> <em>loop constructs</em> </strong> , the <strong> <em>do-while loop</em> </strong> can be <strong> <em>nested</em> </strong> inside other <strong> <em>loops</em> </strong> or <strong> <em>control structures</em> </strong> to create more complex control flow patterns. It allows for the creation of <strong> <em>nested loops</em> </strong> and the implementation of intricate repetitive tasks. </tr><tr><td>Break and Continue:</td> The break statement can be used within a <strong> <em>do-while loop</em> </strong> to terminate the loop execution and exit the loop prematurely. The <strong> <em>continue statement</em> </strong> can skip the remaining code in the current iteration and jump to the next iteration of the loop. </tr><tr><td>Local Scope:</td> Variables declared inside the <strong> <em>do-while loop</em> </strong> body have local scope and are accessible only within the <strong> <em>loop block.</em> </strong> They cannot be accessed outside the loop or by other loops or control structures. </tr><tr><td>Infinite Loop Control:</td> It is crucial to ensure that the loop&apos;s condition is eventually modified within the <strong> <em>loop body</em> </strong> . This modification is necessary to prevent infinite loops where the condition continually evaluates to true. Modifying the condition ensures that the loop terminates at some point. </tr></ul> <hr></=></pre></=>

El programa calcula e imprime la tabla de multiplicar para 7 del 1 al 10.

Bucle infinito do while

Un Bucle infinito es un bucle que se ejecuta indefinidamente ya que su condición es siempre verdadero o carece de una condición de terminación. He aquí un ejemplo de un bucle infinito do... while Cª:

Ejemplo:

 #include int main() { inti = 1; do { printf(&apos;Iteration %d
&apos;, i); i++; } while (1); // Condition is always true return 0; } 

En esto ejemplo , el bucle seguirá corriendo indefinidamente porque condición 1 es siempre verdadero .

Producción:

Al ejecutar el programa verás que continúa imprimiendo. 'Iteración x', donde x es el número de iteración sin parar:

 Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 ... (and so on) 

Para interrumpir un bucle infinito como este, generalmente se utiliza un declaración de ruptura dentro de bucle o alguna condición externa que puedas controlar, como golpeando una combinación de teclas específica. En la mayoría de las configuraciones de escritorio, el método abreviado de teclado Ctrl+C puede escapar del bucle.

Bucle anidado do while en C

En C, tomamos un ejemplo de un bucle anidado do... while . En este ejemplo, escribiremos un programa que utilice bucles anidados do... while para crear un patrón numérico.

Ejemplo:

 #include int main() { int rows, i = 1; printf(&apos;Enter the number of rows: &apos;); scanf(&apos;%d&apos;, &amp;rows); do { int j = 1; do { printf(&apos;%d &apos;, j); j++; } while (j <= i); printf(\'
\'); i++; } while (i<="rows);" return 0; < pre> <p>In this program, we use <strong> <em>nested do...while loops</em> </strong> to generate a pattern of numbers. The <strong> <em>outer loop</em> </strong> controls the number of rows, and the <strong> <em>inner loop</em> </strong> generates the numbers for each row.</p> <p> <strong>Output:</strong> </p> <p>Let us say you input five as the number of rows:</p> <pre> Enter the number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, the program generates a pattern of numbers in a <strong> <em>triangular shape</em> </strong> . The <strong> <em>outer loop</em> </strong> iterates over the rows, and the <strong> <em>inner loop</em> </strong> iterates within each row, printing the numbers from 1 up to the current row number.</p> <h2>Difference between while and do while Loop</h2> <p>Here is a tabular comparison between the while loop and the do-while Loop in C:</p> <table class="table"> <tr> <th>Aspect</th> <th>while loop</th> <th>do-while loop</th> </tr> <tr> <td> <strong>Syntax</strong> </td> <td>while (condition) { ... }</td> <td>do { ... } while (condition);</td> </tr> <tr> <td> <strong>Loop Body Execution</strong> </td> <td>Condition is checked before execution.</td> <td>The body is executed before the condition.</td> </tr> <tr> <td> <strong>First Execution</strong> </td> <td>The condition must be true initially.</td> <td>The body is executed at least once.</td> </tr> <tr> <td> <strong>Loop Execution</strong> </td> <td>May execute zero or more times.</td> <td>Will execute at least once.</td> </tr> <tr> <td> <strong>Example</strong> </td> <td>while (i<5) { printf(\'%d
\', i); i++; }< td> <td>do { printf(&apos;%d
&apos;, i); i++; } while (i<5);< td> </5);<></td></5)></td></tr> <tr> <td> <strong>Common Use Cases</strong> </td> <td>When the loop may not run at all.</td> <td>When you want the loop to run at least once.</td> </tr> </table> <p> <strong>While Loop:</strong> The loop body is executed before the condition is checked. If the condition is initially <strong> <em>false</em> </strong> , the loop may not execute.</p> <p> <strong>Do-while Loop:</strong> The <strong> <em>loop body</em> </strong> is executed at least once before the condition is <strong> <em>checked</em> </strong> . This guarantees that the loop completes at least one iteration.</p> <p>When you want the <strong> <em>loop</em> </strong> to run based on a condition that may be <strong> <em>false</em> </strong> at first, use the <strong> <em>while loop</em> </strong> , and when you want the loop to run at least once regardless of the starting state, use the <strong> <em>do-while loop.</em> </strong> </p> <h2>Features of do while loop</h2> <p>The do-while loop in C has several fundamental characteristics that make it an effective programming technique in certain situations. The following are the significant characteristics of the do-while loop:</p> <ul> <tr><td>Guaranteed Execution:</td> Unlike other <strong> <em>loop structures</em> </strong> , the <strong> <em>do-while oop</em> </strong> ensures that the loop body is executed at least once. Because the condition is assessed after the loop body, the code within the loop is performed before the condition is verified. </tr><tr><td>Loop after testing:</td> The <strong> <em>do-while loop</em> </strong> is a post-tested loop which implies that the loop condition is assessed after the loop body has been executed. If the condition is true, the loop body is run once again. This behavior allows you to verify the condition for repetition before ensuring that a given activity is completed. </tr><tr><td>Conditionally Controlled:</td> The loop continues to execute as long as the condition specified after the while keyword remains <strong> <em>true</em> </strong> . When the condition evaluates to <strong> <em>false</em> </strong> , the loop is terminated, and control shifts to the sentence after the loop. </tr><tr><td>Flexibility:</td> The <strong> <em>do-while loop</em> </strong> may be utilized in several contexts. It is typically used in cases where a piece of code must be executed at least once, such as <strong> <em>menu-driven programs, input validation,</em> </strong> or <strong> <em>repetitive computations</em> </strong> . </tr><tr><td>Nesting Capability:</td> Similar to other <strong> <em>loop constructs</em> </strong> , the <strong> <em>do-while loop</em> </strong> can be <strong> <em>nested</em> </strong> inside other <strong> <em>loops</em> </strong> or <strong> <em>control structures</em> </strong> to create more complex control flow patterns. It allows for the creation of <strong> <em>nested loops</em> </strong> and the implementation of intricate repetitive tasks. </tr><tr><td>Break and Continue:</td> The break statement can be used within a <strong> <em>do-while loop</em> </strong> to terminate the loop execution and exit the loop prematurely. The <strong> <em>continue statement</em> </strong> can skip the remaining code in the current iteration and jump to the next iteration of the loop. </tr><tr><td>Local Scope:</td> Variables declared inside the <strong> <em>do-while loop</em> </strong> body have local scope and are accessible only within the <strong> <em>loop block.</em> </strong> They cannot be accessed outside the loop or by other loops or control structures. </tr><tr><td>Infinite Loop Control:</td> It is crucial to ensure that the loop&apos;s condition is eventually modified within the <strong> <em>loop body</em> </strong> . This modification is necessary to prevent infinite loops where the condition continually evaluates to true. Modifying the condition ensures that the loop terminates at some point. </tr></ul> <hr></=>

Explicación:

En este ejemplo, el programa genera un patrón de números en un forma triangular . El bucle exterior itera sobre las filas, y el bucle interior itera dentro de cada fila, imprimiendo los números desde 1 hasta el número de fila actual.

Diferencia entre while y do while Loop

Aquí hay una comparación tabular entre el bucle while y el bucle do- while en C:

Aspecto mientras bucle bucle hacer-mientras
Sintaxis mientras (condición) {...} hacer {...} mientras (condición);
Ejecución del cuerpo del bucle La condición se verifica antes de la ejecución. El cuerpo se ejecuta antes que la condición.
Primera ejecución La condición debe ser verdadera inicialmente. El cuerpo se ejecuta al menos una vez.
Ejecución de bucle Puede ejecutarse cero o más veces. Se ejecutará al menos una vez.
Ejemplo mientras yo<5) { printf(\'%d \', i); i++; }< td> hacer { printf('%d ', i); yo ++; } mientras yo<5);< td>
Casos de uso comunes Cuando es posible que el bucle no se ejecute en absoluto. Cuando desee que el bucle se ejecute al menos una vez.

Mientras bucle: El cuerpo del bucle se ejecuta antes de comprobar la condición. Si la condición es inicialmente FALSO , es posible que el bucle no se ejecute.

Bucle hacer mientras: El cuerpo de bucle se ejecuta al menos una vez antes de que se cumpla la condición. comprobado . Esto garantiza que el bucle complete al menos una iteración.

menú de configuración del teléfono Android

cuando quieras el bucle ejecutar basándose en una condición que puede ser FALSO al principio, use el mientras bucle , y cuando desee que el bucle se ejecute al menos una vez independientemente del estado inicial, utilice el bucle hacer-mientras.

Características del bucle do while

El bucle do- while en C tiene varias características fundamentales que lo convierten en una técnica de programación eficaz en determinadas situaciones. Las siguientes son las características importantes del bucle do- while:

    Ejecución garantizada:a diferencia de otros estructuras de bucle , el hacer mientras oop garantiza que el cuerpo del bucle se ejecute al menos una vez. Debido a que la condición se evalúa después del cuerpo del bucle, el código dentro del bucle se ejecuta antes de verificar la condición.Bucle después de la prueba:El bucle hacer-mientras es un bucle sometido a prueba posterior, lo que implica que la condición del bucle se evalúa después de que se haya ejecutado el cuerpo del bucle. Si la condición es verdadera, el cuerpo del bucle se ejecuta una vez más. Este comportamiento le permite verificar la condición de repetición antes de asegurarse de que se complete una actividad determinada.Controlado condicionalmente:El bucle continúa ejecutándose mientras permanezca la condición especificada después de la palabra clave while. verdadero . Cuando la condición se evalúa como FALSO , el ciclo finaliza y el control cambia a la oración después del ciclo.Flexibilidad:El bucle hacer-mientras puede utilizarse en varios contextos. Normalmente se utiliza en casos en los que un fragmento de código debe ejecutarse al menos una vez, como por ejemplo programas controlados por menús, validación de entradas, o cálculos repetitivos .Capacidad de anidamiento:Similar a otros construcciones de bucle , el bucle hacer-mientras puede ser anidado dentro de otro bucles o Estructuras de Control para crear patrones de flujo de control más complejos. Permite la creación de bucles anidados y la implementación de complejas tareas repetitivas.Romper y continuar:La declaración de ruptura se puede utilizar dentro de un bucle hacer-mientras para finalizar la ejecución del bucle y salir del bucle prematuramente. El continuar declaración Puede omitir el código restante en la iteración actual y saltar a la siguiente iteración del bucle.Alcance local:Variables declaradas dentro del bucle hacer-mientras organismo tienen alcance local y son accesibles sólo dentro del bloque de bucle. No se puede acceder a ellos fuera del bucle ni mediante otros bucles o estructuras de control.Control de bucle infinito:Es crucial garantizar que la condición del bucle eventualmente se modifique dentro del cuerpo de bucle . Esta modificación es necesaria para evitar bucles infinitos donde la condición se evalúa continuamente como verdadera. Modificar la condición garantiza que el bucle termine en algún punto.