logo

C의 For 대 While 루프

for 루프와 while 루프의 차이점 이해

for 루프, while 루프 및 do-while 루프와 같은 C++의 반복 문을 사용하면 조건이 true가 될 때까지 일련의 명령어를 반복적으로 실행한 다음 조건이 false가 되면 종료됩니다. 반복 문에는 for 루프와 같이 미리 정의된 조건이나 while 루프와 같이 개방형 조건이 있을 수 있습니다.

C++에서는 언어의 적용성, 성능 및 유연성을 높이기 위해 다양한 'for' 루프 변형이 암시됩니다. 예를 들어 for 루프를 사용하면 내부에 여러 변수를 사용하고 'for' 루프와 함께 수렴 기능을 사용하여 루프를 제어할 수 있습니다. 대조적으로, while 루프에서는 많은 변형을 사용할 수 없습니다. 표준 구문과 함께 사용해야 합니다.

for 루프와 while 루프 사이에는 몇 가지 중요한 차이점이 있으며, 이에 대해서는 비교 차트를 사용하여 자세히 설명합니다.

C의 For 대 While 루프

For 루프는 다음과 같이 정의됩니다.

Java에는 두 가지 유형의 for 루프가 있습니다. 첫 번째는 '전통적인' 형식이고 두 번째는 'for-each' 형식입니다.

for 루프 문의 가장 일반적인 형태입니다.

 for (initialization; condition; iteration) { //body of for loop } 
    초기화:for 루프의 루프 제어 변수는 루프의 첫 번째 반복 중에 한 번만 초기화됩니다. 루프 제어 변수는 여기에서 초기화됩니다. 루프 변수가 프로그램에서 다시 사용되지 않고 루프의 제어 변수로만 사용되는 경우 'for' 루프에서 선언되고 초기화됩니다.상태:for 루프의 조건은 루프가 반복될 때마다 실행됩니다.
  • 반복문은 루프 제어 변수를 증가시키거나 감소시키는 표현식입니다.

루프가 실행되면 초기화 조건이 먼저 실행된 후 조건 확인이 수행됩니다. 조건이 충족되면 루프 본문이 실행되고 이어서 반복문이 실행됩니다. 그런 다음 조건을 다시 확인하여 루프가 더 반복될지 아니면 종료될지 결정합니다.

Java에서는 초기화 문과 반복 문에 모두 여러 문이 포함될 수 있습니다. 각 명령문은 쉼표로 구분됩니다. Java에서 쉼표는 구분 기호입니다. C++에서 쉼표는 유효한 모든 표현식에 사용할 수 있는 연산자입니다.

for-each 루프의 구문

'for-each' 형식은 for 루프의 고급 버전입니다. for-each 루프는 다음과 같은 일반적인 형식을 취합니다.

 for(type iter_variable: collection) statement-block 

'type' 매개변수는 반복 변수의 유형을 지정하며 그 뒤에는 반복 변수가 옵니다. 컬렉션 변수의 요소가 반복 변수로 전달됩니다. 유형은 컬렉션 변수의 요소 유형과 일치해야 합니다. for 루프의 for-each 형식은 루프의 반복을 처음부터 끝까지 자동화하여 순차적인 순서로 값에 액세스합니다.

for 루프와 함께 사용할 수 있는 다양한 유형의 컬렉션이 있습니다. 배열을 컬렉션으로 사용하는 방법에 대해 이야기해 보겠습니다.

 public class Main { public static void main(String[] args) { int array[]={10, 20, 30, 40, 50, 60}; int add=0; for( int c: array) { System.out.println( 'value in c ' + c); add = add+c; } System.out.println('additon of array elements is ' +add); } } 

산출:

 value in c 10 value in c 20 value in c 30 value in c 40 value in c 50 value in c 60 additon of array elements is 210 

이 경우 'c'는 반복 변수입니다. 배열의 가장 낮은 인덱스부터 가장 높은 인덱스까지 array[]에서 값을 하나씩 받습니다. 루프는 배열의 모든 요소가 검사될 때까지 반복됩니다. 'break'를 사용하면 루프를 중간에 끊을 수 있습니다. 반면에 반복 변수의 변경은 읽기 전용 변수이기 때문에 배열에 영향을 주지 않습니다.

While 루프는 다음과 같이 정의됩니다.

while 루프는 C++와 Java 모두에서 가장 기본적인 루프입니다. while 루프의 작업은 C++와 Java에서 유사합니다.

통사론

다음은 while 루프 선언입니다.

 while ( condition) { statements; //body of loop } 

while 루프는 먼저 조건을 확인한 다음 while 루프의 조건이 true가 될 때까지 명령문을 실행합니다. while 루프에서 조건은 모든 부울 표현식이 될 수 있습니다. 표현식이 0이 아닌 값을 반환하면 조건은 true입니다. 0 값을 반환하면 조건은 false입니다.

SSH 전체 형식

조건이 true이면 루프가 자체적으로 반복됩니다. 조건이 거짓이면 루프 바로 다음 코드 줄로 제어가 전달됩니다. 본문 루프나 명령문은 빈 명령문, 단일 명령문 또는 명령문 블록일 수 있습니다.

while 루프가 어떻게 작동하는지 살펴보겠습니다. 아래 예제의 코드는 1부터 10까지 인쇄합니다.

 public class Main { public static void main (String args[]) { int n=0; while(n<10) { n++; system.out.println('n=" +n); } } } &lt;/pre&gt; &lt;p&gt; &lt;strong&gt;Output:&lt;/strong&gt; &lt;/p&gt; &lt;pre&gt; n=1 n=2 n=3 n=4 n=5 n=6 n=7 n=8 n=9 n=10 &lt;/pre&gt; &lt;p&gt;The initial value of " n' in this case is 0, which makes the condition while loop true. control then enters loop's body, where value of 'n' incremented accordance with first statement.< p> <p>The value of &apos;n&apos; is printed, then control returns to the condition in a while loop, where the value of &apos;n&apos; is now 1, satisfying the condition once more, and the body of the loop is executed once more. This continues until the condition becomes false, at which point the loop is terminated.</p> <p>The &apos;while&apos; loop, like the &apos;for&apos; loop, can initialise the control variable at the beginning of the loop, i.e. during condition checking.</p> <pre> //for example while((ch = getchar( ) ) != &apos;A&apos;) { System.out.println(&apos; The input alphabet &apos; +ch); } </pre> <p>At the top of the loop, the control variable &apos;ch&apos; is initialised, and the loop&apos;s condition is verified.</p> <h4>Note: If there is only one statement in the body of the loop, whether it is a for loop or a while loop, the curly braces are not required.</h4> <h3>In C, what is the difference between a for loop and a while?</h3> <table class="table"> <tr> <th>Parameters</th> <th>For Loop</th> <th>While Loop</th> </tr> <tr> <td> <strong>Declaration</strong> </td> <td>for(initialization ; condition ; iteration ) { <br> //body of &apos;for&apos; loop <br> }</td> <td>initialization <br>while ( condition ) { <br>statements; <br>//body of loop <br>}</td> </tr> <tr> <td> <strong>Format.</strong> </td> <td>At the top of the loop, initialization, condition checking, and iteration statements are written.</td> <td>At the top of the loop, only initialization and condition checking are performed.</td> </tr> <tr> <td> <strong>Use.</strong> </td> <td>The &apos;for&apos; loop was only used when the number of iterations was already known.</td> <td>When the number of iterations is unknown, the &apos;while&apos; loop is used.</td> </tr> <tr> <td> <strong>Condition.</strong> </td> <td>If the condition is not included in the &apos;for&apos; loop, the loop iterates indefinitely.</td> <td>If the condition is not included in the &apos;while&apos; loop, a compilation error occurs.</td> </tr> <tr> <td> <strong>Initialization</strong> </td> <td>The initialization is never repeated in a &apos;for&apos; loop.</td> <td>If initialization is performed during condition checking in a while loop, initialization is performed each time the loop iterates.</td> </tr> <tr> <td> <strong>Iteration assertion</strong> </td> <td>Because the iteration statement in the &apos;for&apos; loop is written at the top, it executes only after all statements in the loop have been executed.</td> <td>The iteration statement in a &apos;while&apos; loop can be written anywhere in the loop.</td> </tr> </table> <h2>The Key Differences Between for and while loop</h2> <ul> <li>Initialization, condition checking, and increment or decrement of iteration variables are all done explicitly in the loop syntax only. In contrast, in the while loop, we can only initialise and check the condition in the loop syntax.</li> <li>When we know the number of iterations that must occur in a loop execution, we use the for loop. On the other hand, if we do not know how many iterations must occur in a loop, we use a while loop.</li> <li>If you do not include a condition statement in the for loop, the loop will loop indefinitely. In contrast, failing to include a condition statement in the while loop will result in a compilation error.</li> <li>The initialization statement in the for loop syntax is only executed once at the beginning of the loop. If the while loop&apos;s syntax includes an initialization statement, the initialization statement will be executed each time the loop iterates.</li> <li>The iteration statement in the for loop will run after the body of the for loop. On the contrary, because the iteration statement can be written anywhere in the body of the while loop, there may be some statements that execute after the iteration statement in the body of the while loop is executed.</li> </ul> <h2>Conclusion</h2> <p>Loops are thus a collection of commands that must be used in a specific order. If the loop structure is incorrect, the programming will display the syntax error. Loops run to obtain a result or to satisfy a condition or set of conditions. It is the foundation of all programming languages.</p> <p>During execution, the loop structure asks a question and executes until the answer is satisfactory. The same question is asked again and again until the new statement is applied. The looping process continues indefinitely until the programme reaches a breakpoint. In the event that the breaking point is not reached, the programme will crash.</p> <p>The for and while loops are both conditional statements. A for loop is a single-line command that will be executed repeatedly. While loops can be single-lined or contain multiple commands for a single condition.</p> <p>Both the for loop and the while loop are important in computer languages for obtaining results. The condition is met if the command syntax is correct.</p> <p>Both the for loop and the while loop are iteration statements, but they have distinct characteristics. The for loop declares everything (initialization, condition, iteration) at the top of the loop body. In contrast, only initialization and condition are at the top of the body of the loop in a while loop, and iteration can be written anywhere in the body of the loop.</p> <hr></10)>

루프 상단에서는 제어 변수 'ch'가 초기화되고 루프의 상태가 확인됩니다.

참고: for 루프이든 while 루프이든 루프 본문에 명령문이 하나만 있는 경우 중괄호가 필요하지 않습니다.

C에서 for 루프와 while의 차이점은 무엇입니까?

매개변수 For 루프 while 루프
선언 for(초기화; 조건; 반복) {
//'for' 루프의 본문
}
초기화
동안(조건) {
진술;
//루프 본문
}
체재. 루프 상단에는 초기화, 조건 확인 및 반복 문이 작성됩니다. 루프 상단에서는 초기화와 조건 확인만 수행됩니다.
사용. 'for' 루프는 반복 횟수가 이미 알려진 경우에만 사용되었습니다. 반복 횟수를 알 수 없는 경우 'while' 루프가 사용됩니다.
상태. 'for' 루프에 조건이 포함되지 않으면 루프는 무한정 반복됩니다. 조건이 'while' 루프에 포함되지 않으면 컴파일 오류가 발생합니다.
초기화 초기화는 'for' 루프에서 반복되지 않습니다. while 루프에서 조건 확인 중에 초기화를 수행하면 루프가 반복될 때마다 초기화가 수행됩니다.
반복 주장 'for' 루프의 반복문은 맨 위에 작성되므로 루프의 모든 명령문이 실행된 후에만 실행됩니다. while 루프의 반복문은 루프의 어느 위치에나 작성할 수 있습니다.

for 루프와 while 루프의 주요 차이점

  • 초기화, 조건 검사, 반복 변수의 증가 또는 감소는 모두 루프 구문에서만 명시적으로 수행됩니다. 반면에 while 루프에서는 루프 구문에서 조건을 초기화하고 확인할 수만 있습니다.
  • 루프 실행에서 발생해야 하는 반복 횟수를 알 때 for 루프를 사용합니다. 반면에 루프에서 얼마나 많은 반복이 발생해야 하는지 모르는 경우 while 루프를 사용합니다.
  • for 루프에 조건문을 포함하지 않으면 루프가 무한정 반복됩니다. 반대로 while 루프에 조건문을 포함하지 않으면 컴파일 오류가 발생합니다.
  • for 루프 구문의 초기화 문은 루프 시작 시 한 번만 실행됩니다. while 루프의 구문에 초기화 문이 포함되어 있으면 루프가 반복될 때마다 초기화 문이 실행됩니다.
  • for 루프의 반복 문은 for 루프 본문 다음에 실행됩니다. 반대로 반복문은 while 루프 본문 어디든 쓸 수 있기 때문에 while 루프 본문의 반복문이 실행된 이후에 실행되는 명령문이 있을 수 있습니다.

결론

따라서 루프는 특정 순서로 사용해야 하는 명령 모음입니다. 루프 구조가 올바르지 않으면 프로그래밍에 구문 오류가 표시됩니다. 루프는 결과를 얻거나 조건 또는 조건 집합을 충족하기 위해 실행됩니다. 모든 프로그래밍 언어의 기초입니다.

실행 중에 루프 구조는 질문을 하고 대답이 만족스러울 때까지 실행됩니다. 새로운 진술이 적용될 때까지 동일한 질문이 계속해서 제기됩니다. 루프 프로세스는 프로그램이 중단점에 도달할 때까지 무한정 계속됩니다. 중단점에 도달하지 않으면 프로그램이 중단됩니다.

for 루프와 while 루프는 모두 조건문입니다. for 루프는 반복적으로 실행되는 한 줄 명령입니다. While 루프는 한 줄로 작성되거나 단일 조건에 대한 여러 명령을 포함할 수 있습니다.

for 루프와 while 루프는 모두 컴퓨터 언어에서 결과를 얻는 데 중요합니다. 명령 구문이 정확하면 조건이 충족됩니다.

for 루프와 while 루프는 모두 반복문이지만 서로 다른 특성을 가지고 있습니다. for 루프는 루프 본문 상단에서 모든 것(초기화, 조건, 반복)을 선언합니다. 반면 while 루프에서는 초기화와 조건만 루프 본문의 상단에 있고 반복은 루프 본문의 어느 곳에나 작성할 수 있습니다.