Java

2024.04.12 반복문( while )

정훈5 2024. 4. 12. 11:02
학습 목표 

while 문에 대한 이해 
무한 루프를 조심하자

 

while문

수행문을 수행하기 전 조건을 체크하고 그 조건의 결과가 true인 동안 반복 수행

 

(그림)

 

조건이 참(true)인 동안 반복수행하기

주어진 조건에 맞는 동안(true) 지정된 수행문을 반복적으로 수행하는 제어문

조건이 맞지 않으면 반복하던 수행을 멈추게 됨

● 조건은 주로 반복 횟수나 값의 비교의 결과에 따라 true, false 판단 됨

 

package basic.ch04;

public class WhileTest1 {
	// 코드의 시작점
	public static void main(String[] args) {
		
		// 1 부터 10 까지 콘솔창에 숫자를 출력하고 싶어!
		
//		System.out.println(1);
//		System.out.println(2);
//		System.out.println(3);
//		System.out.println(4);
//		System.out.println(5);
//		System.out.println(6);
//		System.out.println(7);
//		System.out.println(8);
//		System.out.println(9);
//		System.out.println(10);
//		
		// x <= 10
		int i = 1;
		while(i <=10) {
			System.out.println(i);
			
			// while 구문은 조건식에 처리가 없다면 무한이 반복한다.
			// i++;
			// i = i+1;
			i+=1;
		
		} // end of while
	
	} // end of main

} // end of class
package basic.ch04;

public class whileTest2 {
	// 코드의 시작 (메인함수)
	public static void main(String[] args) {
		
		// start = 0;
		// end = 사용자가 입력한 값
		// 화면에 0부터 사용자가 입력한 값 까지 반복해서 출력해 보자.
		
		// 특정 조건일 때 반복문을 종료 시켜 보자.
		boolean flag = true; // 깃발
		int start = 1;
		int end = 3;
		
		while(flag) {
			if(start == end) {
				System.out.println("if 구문이 동작함");
				flag = false;
				return;
				
			} // end of if
			
			System.out.println("start : " + start);
			
			start++;
		} // end of while

	} // end of main

} // end of class

 

연습 문제

1 부터 10까지 덧셈에 연산을 콘솔창에 출력 하시오 단, while 구문 작성

package basic.exercise;

public class Practice_while {
	// 코드의 시작
	public static void main(String[] args) {
		
		int start = 1;
		int end = 100;
		int sum = 0;
		
		while(start <= end) {
			sum = sum + start;
			System.out.println("start : " + start);
			start++;
		} System.out.println("sum : " + sum);
	
	} // end of main

} // end of class

 

package basic.ch04;

public class whileTest2_1 {

	public static void main(String[] args) {

		// 1 부터 5 까지 덧셈 연산을 하라
		// 1 + 2 + 3 + 4 + 5

		int start = 1; // 시작값은 1
		int end = 5; // 끝 값은 5
		int sum = 0;
		// 첫번째 반복
		// 6번째
		// 6 <= 5 --> 거짓 --> 반복문 종료
		
		// 특정 조건식을 만들어 반복문을 멈추게 해야 한다.
		// 만약 start 값이 10일 때 종료 하라
		boolean flag = true;
		while (flag) {
			
			if(start == 10) {
				// 실행에 제어권을 반납한다.
				// return
				flag = false;
			}

			// 1 = 0 + 1 ==> sum : 1
			// 2 = 1 + 2 ==> sum : 3
			// 3 = 3 + 3 ==> sum : 6
			// 4 = 6 + 4 ==> sum : 10
			// 5 = 10 + 5 ==> sum : 15
			sum = sum + start;
			System.out.println("sum(" + start + ") : " + sum);

			start++; // 1씩 증가

		}

	}

}