logo

faire une boucle while en C

UN boucle est une structure de contrôle de programmation qui vous permet d'exécuter un bloc de code indéfiniment si une condition spécifique est remplie. Les boucles sont utilisées pour exécuter des activités répétitives et améliorer les performances de programmation. Il existe plusieurs boucles dans le langage de programmation C, dont l'une est la boucle 'faire pendant' .

UN boucle 'faire pendant' est une forme de boucle en C qui exécute le bloc de code en premier, suivi de la condition. Si la condition est vrai , le boucle continue de fonctionner ; sinon, ça s'arrête. Cependant, que la condition soit initialement vrai , il garantit que le bloc de code est exécuté au moins une fois.

faire la syntaxe de la boucle while

La syntaxe de la boucle do-while du langage C est donnée ci-dessous :

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

Les composants sont répartis comme suit :

formulaire complet cdr
  • Le faire un mot clé marque le début de la boucle.
  • Le bloc de code dans accolades {} est le corps de la boucle, qui contient le code que vous souhaitez répéter.
  • Le while mot-clé est suivi d'une condition entre parenthèses (). Une fois le bloc de code exécuté, cette condition est vérifiée. Si la condition est vrai , la boucle continue sinon, le la boucle se termine .

Fonctionnement de la boucle do while en C

Regardons un exemple de la façon dont un faire une boucle en attendant fonctionne en C. Dans cet exemple, nous allons écrire un programme simple qui interroge l'utilisateur pour un mot de passe et continue de demander jusqu'à ce que le bon mot de passe soit saisi.

Exemple:

 #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; } 

Le programme se déroule comme suit :

  1. Les fichiers d'en-tête suivants sont inclus : pour la norme saisir et sortir routines et pour chaîne fonctions de manipulation .
  2. Le mot de passe correct est défini comme un tableau de caractères (char password[]) avec la valeur 'secrète'
  3. Après cela, nous définissons une autre entrée de tableau de caractères pour stocker l'entrée de l'utilisateur.
  4. Le faire un mot clé indique que le bloc de code inclus dans le boucle sera effectué au moins une fois.
  5. En utilisant le Fonction printf() , nous affichons une invite demandant à l'utilisateur de saisir son mot de passe dans la boucle.
  6. Ensuite, nous lisons le contribution de l'utilisateur en utilisant le Fonction scanf() et rangez-le dans le tableau d'entrée .
  7. Après avoir lu le saisir , nous utilisons le Fonction strcmp() pour comparer l'entrée avec le mot de passe correct. Si les chaînes sont égal, le fonction strcmp renvoie 0. Nous continuons donc à boucler tant que l'entrée et le mot de passe ne sont pas égaux.
  8. Une fois la mot de passe correct est entré, la boucle se termine et nous imprimons 'Accès autorisé!' en utilisant le Fonction printf() .
  9. Après cela, le programme renvoie 0 pour indiquer une exécution réussie.

Sortir:

Passons en revue un scénario possible :

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

Explication:

Dans cet exemple, l'utilisateur saisit initialement les mauvais mots de passe, '123' et 'abc' . La boucle invite l'utilisateur jusqu'à ce que le mot de passe correct 'secrète' est saisi. Une fois le mot de passe correct fourni, la boucle se termine et le 'Accès autorisé!' message s'affiche.

Exemple de boucle do while en C :

Exemple 1:

Voici un exemple simple de boucle 'faire pendant' en C qui imprime les nombres de 1 à 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></=>

Explication:

Dans cet exemple, le bloc de code dans la boucle do sera exécuté au moins une fois, imprimant les nombres de 1 à 5 . Après chaque itération, le j'apprécie est incrémenté, et la condition je<= 5< em> est vérifié. Si la condition est toujours vraie, la boucle continue ; sinon, il se termine.

Exemple 2 :

Programme pour imprimer le tableau pour le nombre donné en utilisant 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);>

Exemple 3 :

Prenons un programme qui imprime la table de multiplication d'un nombre N donné en utilisant un faire... pendant que la boucle :

 #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></=>

Le programme calcule et imprime la table de multiplication pour 7 de 1 à 10.

Boucle infinie do while

Un boucle infinie est une boucle qui s'exécute indéfiniment car sa condition est toujours vrai ou il lui manque une condition de fin. Voici un exemple de infini faire... while boucle en C :

Exemple:

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

Dans ce exemple , le boucle continuera à courir indéfiniment parce que état 1 est toujours vrai .

Sortir:

Lorsque vous exécutez le programme, vous verrez qu'il continue d'imprimer 'Itération x', où x est le numéro d'itération sans s'arrêter:

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

Pour interrompre une boucle infinie comme celle-ci, vous utilisez généralement un instruction de pause au sein de boucle ou une condition externe que vous pouvez contrôler, telle que frappe une combinaison de touches spécifique. Dans la plupart des paramètres du bureau, le raccourci clavier Ctrl+C peut échapper à la boucle.

Boucle do while imbriquée en C

En C, nous prenons un exemple de imbriqué do...while boucle . Dans cet exemple, nous allons écrire un programme qui utilise boucles do... while imbriquées pour créer un modèle numérique.

Exemple:

 #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></=>

Explication:

Dans cet exemple, le programme génère une suite de nombres dans un forme triangulaire . Le boucle externe parcourt les lignes, et le Boucle intérieure itère dans chaque ligne, imprimant les nombres de 1 jusqu'au numéro de ligne actuel.

Différence entre while et do while Boucle

Voici une comparaison tabulaire entre la boucle while et la boucle do-while en C :

Aspect boucle while faire une boucle en attendant
Syntaxe tandis que (condition) { ... } faire { ... } while (condition);
Exécution du corps de la boucle La condition est vérifiée avant l’exécution. Le corps est exécuté avant la condition.
Première exécution La condition doit être vraie initialement. Le corps est exécuté au moins une fois.
Exécution en boucle Peut s'exécuter zéro ou plusieurs fois. S'exécutera au moins une fois.
Exemple alors que je<5) { printf(\'%d \', i); i++; }< td> faire { printf('%d ', i); je++; } alors que je<5);< td>
Cas d'utilisation courants Lorsque la boucle peut ne pas fonctionner du tout. Lorsque vous souhaitez que la boucle s'exécute au moins une fois.

Boucle While : Le corps de la boucle est exécuté avant que la condition ne soit vérifiée. Si la condition est initialement FAUX , la boucle peut ne pas s'exécuter.

Boucle à faire pendant : Le corps de boucle est exécuté au moins une fois avant que la condition ne soit vérifié . Cela garantit que la boucle termine au moins une itération.

tutoriel java jfx

Quand tu veux le boucle fonctionner en fonction d'une condition qui peut être FAUX dans un premier temps, utilisez le boucle while , et lorsque vous souhaitez que la boucle s'exécute au moins une fois quel que soit l'état de départ, utilisez le faire une boucle while.

Caractéristiques de la boucle do while

La boucle do while en C possède plusieurs caractéristiques fondamentales qui en font une technique de programmation efficace dans certaines situations. Voici les caractéristiques importantes de la boucle do-while :

    Exécution garantie :contrairement à d'autres structures en boucle , le faire en attendant oups garantit que le corps de la boucle est exécuté au moins une fois. Étant donné que la condition est évaluée après le corps de la boucle, le code dans la boucle est exécuté avant que la condition ne soit vérifiée.Boucle après test :Le faire une boucle en attendant est une boucle post-testée qui implique que la condition de la boucle est évaluée après l'exécution du corps de la boucle. Si la condition est vraie, le corps de la boucle est à nouveau exécuté. Ce comportement vous permet de vérifier la condition de répétition avant de vous assurer qu'une activité donnée est terminée.Contrôlé sous condition :La boucle continue de s'exécuter tant que la condition spécifiée après le mot-clé while reste vrai . Lorsque la condition est évaluée à FAUX , la boucle est terminée et le contrôle passe à la phrase après la boucle.La flexibilité:Le faire une boucle en attendant peut être utilisé dans plusieurs contextes. Il est généralement utilisé dans les cas où un morceau de code doit être exécuté au moins une fois, comme programmes pilotés par menu, validation des entrées, ou calculs répétitifs .Capacité de nidification :Semblable à d'autres constructions de boucles , le faire une boucle en attendant peut être imbriqué à l'intérieur d'un autre boucles ou Structures de contrôle pour créer des modèles de flux de contrôle plus complexes. Il permet de créer boucles imbriquées et la mise en œuvre de tâches répétitives complexes.Pause et continuation :L'instruction break peut être utilisée dans un faire une boucle en attendant pour terminer l’exécution de la boucle et quitter la boucle prématurément. Le continuer la déclaration peut ignorer le code restant dans l'itération en cours et passer à l'itération suivante de la boucle.Portée locale :Variables déclarées à l'intérieur du faire une boucle en attendant corps ont une portée locale et ne sont accessibles qu’au sein du bloc de boucle. Ils ne sont pas accessibles en dehors de la boucle ou par d’autres boucles ou structures de contrôle.Contrôle de boucle infinie :Il est crucial de s'assurer que l'état de la boucle est éventuellement modifié dans le corps de boucle . Cette modification est nécessaire pour éviter les boucles infinies où la condition est continuellement évaluée comme vraie. La modification de la condition garantit que la boucle se termine à un moment donné.