예제가 포함된 Java while 루프
자바 while 루프 주어진 부울 조건에 따라 코드가 반복적으로 실행되도록 하는 제어 흐름 문입니다. while 루프는 if 문을 반복하는 것으로 생각할 수 있습니다. Java의 while 루프는 명령문 블록을 반복적으로 실행해야 할 때 사용됩니다. while 루프는 반복되는 if 문으로 간주됩니다. 반복 횟수가 고정되어 있지 않은 경우 while 루프를 사용하는 것이 좋습니다.
통사론:
while (test_expression) { // statements update_expression; } 메모: while( 조건 ) 뒤에 중괄호 '{' 및 '}'를 제공하지 않으면 기본적으로 while 문은 바로 옆에 있는 문을 해당 블록 안에 있는 것으로 간주합니다.
동안(테스트_표현)
// while의 단일 명령문
Java While 루프의 일부
다양한 While 루프의 일부 이다:
1. 테스트 표현: 이 표현식에서는 조건을 테스트해야 합니다. 조건이 true로 평가되면 루프 본문을 실행하고 표현식 업데이트로 이동합니다. 그렇지 않으면 while 루프를 종료합니다.
예:
i <= 10
2. 표현식 업데이트 : 루프 본문을 실행한 후 이 표현식은 루프 변수를 특정 값만큼 증가/감소시킵니다.
예:
i++;
While 루프는 어떻게 실행됩니까?
- 제어는 while 루프에 속합니다.
- 흐름이 조건으로 점프합니다.
- 상태가 테스트되었습니다.
- Condition이 true를 산출하면 흐름이 Body로 들어갑니다.
- Condition이 false를 생성하면 흐름이 루프 외부로 이동합니다.
- 루프 본문 내부의 명령문이 실행됩니다.
- 업데이트가 이루어집니다.
- 제어 흐름은 2단계로 다시 돌아갑니다.
- while 루프가 종료되고 흐름이 외부로 나갔습니다.
while 루프(제어 흐름)의 흐름도:
Java while 루프의 예
예시 1: 이 프로그램은 Hello World를 5번 인쇄하려고 시도합니다.
자바
// Java program to illustrate while loop.> class> whileLoopDemo {> > public> static> void> main(String args[])> > {> > // initialization expression> > int> i => 1> ;> > // test expression> > while> (i <> 6> ) {> > System.out.println(> 'Hello World'> );> > // update expression> > i++;> > }> > }> }> |
산출
Hello World Hello World Hello World Hello World Hello World
위 방법의 복잡성:
시간 복잡도: 오(1)
보조 공간 : 오(1)
공회전 예 1: 프로그램은 다음과 같은 방식으로 실행됩니다.
1. Program starts. 2. i is initialized with value 1. 3. Condition is checked. 1 <6 yields true. 3.a) 'Hello World' gets printed 1st time. 3.b) Updation is done. Now i = 2. 4. Condition is checked. 2 <6 yields true. 4.a) 'Hello World' gets printed 2nd time. 4.b) Updation is done. Now i = 3. 5. Condition is checked. 3 <6 yields true. 5.a) 'Hello World' gets printed 3rd time 5.b) Updation is done. Now i = 4. 6. Condition is checked. 4 <6 yields true. 6.a) 'Hello World' gets printed 4th time 6.b) Updation is done. Now i = 5. 7. Condition is checked. 5 <6 yields true. 7.a) 'Hello World' gets printed 5th time 7.b) Updation is done. Now i = 6. 8. Condition is checked. 6 <6 yields false. 9. Flow goes outside the loop. Program terminates.
예시 2: 이 프로그램은 1부터 10까지의 숫자의 합을 구하는 프로그램입니다.
자바
// Java program to illustrate while loop> class> whileLoopDemo {> > public> static> void> main(String args[])> > {> > int> x => 1> , sum => 0> ;> > // Exit when x becomes greater than 4> > while> (x <=> 10> ) {> > // summing up x> > sum = sum + x;> > // Increment the value of x for> > // next iteration> > x++;> > }> > System.out.println(> 'Summation: '> + sum);> > }> }> |
산출
Summation: 55
위 방법의 복잡성
시간 복잡도: 오(1)
보조 공간 : 오(1)
Java while 루프에 대한 비디오 참조
관련 기사:
- Java의 루프
- 예제가 포함된 Java For 루프
- 예제가 포함된 Java do-while 루프
- C, C++, Java의 for 루프와 while 루프의 차이점
- C, C++, Java의 while과 do-while 루프의 차이점