반복문( while ) - 20

반복문( while ) - 20

💡 학습 목표
    1. while 문에 대한 이해
    2. 무한 루프를 조심하자

1. while문

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

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

  • 주어진 조건에 맞는 동안(true) 지정된 수행문을 반복적으로 수행하는 제어문
  • 조건이 맞지 않으면 반복하던 수행을 멈추게 됨
  • 조건은 주로 반복 횟수나 값의 비교의 결과에 따라 true, false 판단 됨

code. WhileTest1

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);
			i++;
			
			// while 구문은 조건식의 처리가 없다면 무한히 반복한다.
			
		} // end of while
		
		
	} // end of main

} // end of class

code. WhileTest2

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;
			} // end of if
			System.out.println("start : " + start);
			start++;
		} // end of while

	} // end of main

} // end of class

* 특정 조건  ⇒  if문을 떠올리기

  if 문 안에 while 조건식을 false로 만들 수 있는 코드를 작성

* return : while을 그 자리에서 끝내게함

  return이 없다면 while문을 끝까지 수행

 

연습 문제

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

code. WhileExercise

package basic.exercise;

public class WhileExercise {

	public static void main(String[] args) {

		int i = 1;
		int sum = 0;
		while (i <= 10) {
			sum += i;
			System.out.println("sum : " + sum);
			i++;
		}
		
		
	}

}

 

for문과 while문 차이

  • for문은 반복횟수가 정해져있을때
  • while문은 반복횟수가 정해져 있지 않을때

Java 기초 문법 - 1 으로 돌아가기

 

'Java > Java 기초 문법' 카테고리의 다른 글

반복문과 조건문 { 연습문제 } - 22  (0) 2024.04.12
break, continue 사용 - 21  (0) 2024.04.12
반복문( for ) - 19  (0) 2024.04.11
조건문 if(만약 … 이라면) - 18  (0) 2024.04.11
연산자 (연습 문제) - 17  (0) 2024.04.11