logo

направете цикъл докато в C

А цикъл е структура за програмен контрол, която ви позволява да изпълнявате a блок от код за неопределено време, ако е изпълнено определено условие. Циклите се използват за изпълнение на повтарящи се дейности и повишаване на производителността на програмирането. В езика за програмиране C има множество цикли, един от които е цикъл 'до-докато'. .

А цикъл 'до-докато'. е форма на a цикъл в C, който първо изпълнява кодовия блок, последван от условието. Ако условието е вярно , на цикъл продължава да тече; в противен случай спира. Въпреки това, дали състоянието е първоначално вярно , той гарантира, че кодовият блок се изпълнява поне веднъж.

do while синтаксис на цикъл

Синтаксисът на do-while цикъла на езика C е даден по-долу:

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

Компонентите са разделени на следните:

универсалност в java
  • The do ключова дума бележи началото на цикъла.
  • The кодов блок в рамките на фигурни скоби {} е тялото на цикъла, което съдържа кода, който искате да повторите.
  • The докато ключова дума е последвано от условие, оградено в скоби (). След като кодовият блок е изпълнен, това условие се проверява. Ако условието е вярно , цикълът продължава else, the цикъл завършва .

Работа на do while Loop в C

Нека разгледаме пример за това как a do-while цикъл работи в C. В този пример ще напишем проста програма, която задава въпроси на потребителя за a парола и продължава да пита, докато не бъде въведена правилната парола.

Пример:

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

Програмата работи по следния начин:

  1. Включени са следните заглавни файлове: за стандарт вход и изход съчетания и за низ манипулационни функции .
  2. Правилната парола се определя като a масив от знаци (char парола[]) със стойността 'тайна'
  3. След това дефинираме друг входен масив от знаци за съхраняване на въведеното от потребителя.
  4. The do ключова дума показва, че кодовият блок, включен в цикъл ще се извърши поне веднъж.
  5. Използвайки функция printf(). , показваме подкана, изискваща от потребителя да въведе своята парола в цикъла.
  6. След това четем въвеждане на потребителя използвайки функция scanf(). и го съхранявайте в входен масив .
  7. След прочитане на вход , ние използваме функция strcmp(). за да сравните въведената с правилната парола. Ако струните са равен, на функция strcmp връща 0. И така, продължаваме цикъла, докато входът и паролата не са равни.
  8. Веднъж правилна парола се въвежда, цикълът прекратява и ние отпечатваме „Достъпът е разрешен!“ използвайки функция printf(). .
  9. След това програмата връща 0, за да покаже успешно изпълнение.

Изход:

Нека преминем през възможен сценарий:

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

Обяснение:

В този пример потребителят първоначално въвежда грешни пароли, '123' и 'abc' . Цикълът подканва потребителя до правилната парола 'тайна' е въведено. След като бъде предоставена правилната парола, цикълът прекратява и „Достъпът е разрешен!“ се показва съобщение.

Пример за do while цикъл в C:

Пример 1:

Ето един прост пример за a цикъл 'до-докато'. в C, който отпечатва числа от 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></=>

Обяснение:

В този пример, кодов блок в рамките на do цикъла ще се изпълни поне веднъж, отпечатвайки числа от 1 до 5 . След всяка итерация, ценя се увеличава, а условието i<= 5< em> се проверява. Ако условието все още е вярно, цикълът продължава; в противен случай се прекратява.

Пример 2:

Програма за отпечатване на таблица за дадено число с помощта на 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);>

Пример 3:

Нека вземем програма, която отпечатва таблицата за умножение на дадено число N с помощта на a do...while Loop :

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

Програмата изчислява и отпечатва таблицата за умножение за 7 от 1 до 10.

Безкраен do while цикъл

Ан безкраен цикъл е цикъл, който работи за неопределено време, тъй като условието му е винаги вярно или липсва крайно условие. Ето един пример за безкраен do...while цикъл в C:

Пример:

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

В това пример , на цикъл ще продължи да работи за неопределено време защото състояние 1 е винаги вярно .

Изход:

Когато стартирате програмата, ще видите, че тя продължава да печата „Итерация x“, където х е номер на итерация без спиране:

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

За да прекъснете безкраен цикъл като този, обикновено използвате a изявление за прекъсване в рамките на цикъл или някакво външно състояние, което можете да контролирате, като напр удряне конкретна клавишна комбинация. В повечето настройки на работния плот, клавишната комбинация Ctrl+C може да избяга от Примката.

Вложен do while цикъл в C

В C вземаме пример за a вложен do...while цикъл . В този пример ще напишем програма, която използва вложени do...while цикли за създаване на цифров модел.

Пример:

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

Обяснение:

В този пример програмата генерира модел от числа в a триъгълна форма . The външен контур итерира през редовете и вътрешен контур итерира във всеки ред, отпечатвайки числата от 1 до номера на текущия ред.

Разлика между while и do while Loop

Ето таблично сравнение между цикъла while и цикъла do-while в C:

Аспект докато цикъл do-while цикъл
Синтаксис докато (условие) { ... } do { ... } докато (условие);
Изпълнение на тялото на контур Състоянието се проверява преди изпълнение. Тялото се изпълнява преди условието.
Първо изпълнение Първоначално условието трябва да е вярно. Тялото се екзекутира поне веднъж.
Изпълнение на цикъл Може да се изпълни нула или повече пъти. Ще се изпълни поне веднъж.
Пример докато аз<5) { printf(\'%d \', i); i++; }< td> do { printf('%d ', i); i++; } докато аз<5);< td>
Обичайни случаи на употреба Когато цикълът може изобщо да не работи. Когато искате цикълът да се изпълнява поне веднъж.

Докато цикъл: Тялото на цикъла се изпълнява преди условието да бъде проверено. Ако състоянието е първоначално невярно , цикълът може да не се изпълни.

Do-while цикъл: The тяло на примка се изпълнява поне веднъж преди условието да бъде проверено . Това гарантира, че цикълът завършва поне една итерация.

отворете файл с java

Когато искате цикъл да се изпълнява въз основа на състояние, което може да бъде невярно в началото използвайте докато цикъл и когато искате цикълът да се изпълнява поне веднъж, независимо от началното състояние, използвайте do-while цикъл.

Характеристики на do while цикъл

Цикълът do-while в C има няколко основни характеристики, които го правят ефективна техника за програмиране в определени ситуации. Следните са важните характеристики на do-while цикъла:

    Гарантирано изпълнение:За разлика от други контурни структури , на do-while oop гарантира, че тялото на цикъла се изпълнява поне веднъж. Тъй като условието се оценява след тялото на цикъла, кодът в рамките на цикъла се изпълнява преди условието да бъде проверено.Цикъл след тестване:The do-while цикъл е посттестван цикъл, което предполага, че състоянието на цикъла се оценява след като тялото на цикъла е изпълнено. Ако условието е вярно, тялото на цикъла се изпълнява отново. Това поведение ви позволява да проверите условието за повторение, преди да се уверите, че дадена дейност е завършена.Условно контролирани:Цикълът продължава да се изпълнява, докато остава условието, посочено след ключовата дума while вярно . Когато състоянието се оценява на невярно , цикълът се прекратява и контролът се премества към изречението след цикъла.Гъвкавост:The do-while цикъл може да се използва в няколко контекста. Обикновено се използва в случаите, когато част от код трябва да бъде изпълнена поне веднъж, като напр управлявани от менюто програми, валидиране на въвеждане, или повтарящи се изчисления .Възможност за влагане:Подобно на други циклични конструкции , на do-while цикъл може да бъде вложени вътре в други примки или контролни структури за създаване на по-сложни модели на потока на управление. Дава възможност за създаване на вложени цикли и изпълнението на сложни повтарящи се задачи.Прекъсване и продължаване:Операторът break може да се използва в рамките на a do-while цикъл за прекратяване на изпълнението на цикъла и преждевременно излизане от цикъла. The продължи изявление може да пропусне оставащия код в текущата итерация и да премине към следващата итерация на цикъла.Местен обхват:Променливи, декларирани вътре в do-while цикъл тяло имат локален обхват и са достъпни само в рамките на контурен блок. Те не могат да бъдат достъпни извън цикъла или от други контури или контролни структури.Управление на безкраен цикъл:От решаващо значение е да се гарантира, че състоянието на цикъла в крайна сметка се променя в рамките на тяло на примка . Тази модификация е необходима, за да се предотвратят безкрайни цикли, при които условието непрекъснато се оценява като вярно. Промяната на условието гарантира, че цикълът ще приключи в даден момент.