Java

반복문( while )

ryeonng 2024. 4. 12. 14:22

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 clas
package basic.ch04;

public class whileTest2 {

	// 코드의 시작점(메인함수)
	public static void main(String[] args) {

		// 특정 조건일 때 반복문을 종료 시켜 보자.
		boolean flag = true; // 깃발
		int start = 1;
		int end = 3;

		while (flag) {
			if (start == end) {
				System.out.println("if 구문이 동작함");
				flag = false;
				return;
			}
			System.out.println("start : " + start);
			start++;
		} // end of while

	} // end of main

} // end of class

 


연습 문제

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

 

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) {
				// 실행의 제어권을 반납한다.
				flag = false;
				
			}
		//1: 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씩 증가
		}
	}

}

'Java' 카테고리의 다른 글

반복문과 조건문 { 연습문제 }  (0) 2024.04.12
break, continue 사용  (0) 2024.04.12
반복문( for )  (0) 2024.04.12
조건문 if  (1) 2024.04.11
삼항 연산자(조건 연산자)  (1) 2024.04.11