티스토리 뷰

반복문 (Loop문) : 문장들을 반복해서 여러 번 수행되게 할 때 사용하는 구문이다. 구문 상에 반복되는 구간을 루프(Loop) 라고 하며, 루프가 있는 문장이라고 하여 루프(Loop) 문이라고도 한다. 반복문에는 for문, while문이 있다.

 

while : 횟수가 정해지지 않은 반복 처리에 주로 사용되는 반복문으로, for문과 다르게 반복에 대한 조건식만 제시되며 조건식의 결과가 true 일 동안 수행영역 안의 내용이 반복적으로 실행되는 구조로 동작하는 구문이다. 조건식의 결과가 false 일 때 반복을 종료한다.

	while(조건식) {
		//조건식이 참(true)일 경우 실행되는 문장들
	}

 

다음 코드를 통해 while문을 사용 예시를 보도록 하겠다.

package com.test01;

public class MTest01 {

	public static void main(String[] args) {
		//prn01();
		prn02();
		prn03();
		prn04();
		prn05();
	}
	
	public static void prn01() {
		int i = 1;
		
		while(true) {
			System.out.println(i++);
		}
	}
	
	public static void prn02() {
    	// while 문을 for 문처럼 사용할 수도 있는데, 초기식과 증감식을 따로 지정하면 가능하다.
        // 초기식은 while문 사용 전에 선언하고, 증감식은 { } 안에 추가하면 된다.
    
		int i=1;
		
		while(i < 10) {
			System.out.println(i);
			i++;
		}
		System.out.println("i : " + i);
	}
	
	public static void prn03() {
    	// do ~ while
    	// do { } 안의 내용을 일단 한번 실행한 다음, 아래에 있는 while의 조건식의 결과에 따라
        // 블록 안의 내용에 대한 반복 실행을 결정하는 반복문이다.
		do {
			System.out.println("hi!");
		}while(false);
	}
	
	public static void prn04() {
		int i = 1;
		
		do {
			System.out.println(i);
			i++;
		}while(i == 10);
		System.out.println("i : " + i);
	}
	
	public static void prn05() {
		int i=1;
		
		while(true) {
			System.out.println(i);
			i++;
			if(i == 10)
				break;
		}
		System.out.println("i : " + i);
	}
}

 

예제1) 정답 : 

package com.test01;

public class MTest02 {
	public static void main(String[] args) {
		//1. 1~100까지의 숫자를 역순으로 출력하자.
		prn01();
		System.out.println("============================");
		//2. 1~100까지의 숫자 중, 2의 배수만 출력하자.
		prn02();
		System.out.println("============================");
		//3. 1~100까지의 숫자 중, 7의 배수의 갯수와 총 합을 출력하자.
		prn03();
	}
	
	public static void prn01() {
		int i = 100;
		while(i > 0) {
			System.out.println(i);
			i--;
		}
	}
	
	public static void prn02() {
		int i = 2;
		while(i<=100) {
			System.out.println(i);
			i += 2;
		}
	}
	
	public static void prn03() {
		int sum = 0;
		int num = 0;
		int i = 7;
		while(i <= 100) {
			sum += i;
			num++;
			
			i += 7;
		}
		System.out.println("7의 배수의 갯수는 " + num + " 이고, 총 합은 " + sum + " 입니다.");
	}
}

예제2) 정답 : 

package com.test02;

public class MTest01 {

	/*
	 * A B C D E
	 * F G H I J
	 * K L M N O
	 * P Q R S T
	 * U V W X Y 
	 * Z
	 */
	public static void main(String[] args) {

		int count = 0;
		char c = 'A';
		boolean stop = false;

		while (!stop) {
			while (true) {
				System.out.printf("%2c", c);
				c++;
				count++;
				if (count % 5 == 0) {
					break;
				}
				if (count == 26) {
					stop = true;
					break;
				}
			}

			System.out.println();
		}

	}
}

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함