[Study #07] 무한 반복문

 

01. 알고리즘

  • 의미 : 수학과 컴퓨터 과학, 언어학 또는 엮인  분야에서 어떠한 문제를 해결하기 위해 정해진 일련의 절차
  • 문제 풀이에 필요한 계산 절차 또는 처리 과정의 순서
  • 산법, 셈법, 계산 절차

[ 활용 ] num01과 num02 값 바꾸기

int num01 = 10; int num02 = 20; int temp = 0; temp = num01; num01 = num02; num02 = temp; System.out.println(num01); // 20 System.out.println(num02); // 10

 

02. While문

  • 조건식이 true일 경우 무한 반복
  • 조건식이 false가 되면 반복 행위를 멈추고 while문 종료
  • 특정 조건이 되면 탈출
  • 채팅이나 게임 등 무한 반복이 필요한 로직에서 활용

[ 기본 ]

int num = 1; ​​​​while (num <= 10) { ​​​​​​​​System.out.println("참입니다."); ​​​​​​​​num++; ​​​​}//'참입니다'가 10번 출력 ​​​​ ​​​​ boolean b = !true;//오류 안 나는 이유 : b가 변수라서 변할 값이니까 while (b) { ​​​​System.out.println("출력문장"); } System.out.println("while문 밖 문장입니다."); //값 : while문 밖 문장입니다.

 

[ 예제 1 ] y값 받았을 때 종료하기

package jun12; import java.io.IOException; public class While02 { public static void main(String[] args) throws IOException { ‌‌ ‌‌boolean quit = true; ‌‌while (quit) {//조건식을 먼저 검사하고 그 뒤에 출력함 ‌‌‌System.out.println("게임을 시작합니다."); ‌‌‌System.out.println("게임중..."); ‌‌‌System.out.print("게임을 종료할까요?(Y/N) "); ‌‌‌//enter는 \n \r이라는 뜻임 ‌‌‌char input = (char) System.in.read(); ‌‌‌System.in.read(); System.in.read(); //엔터처리 첫번째는 \n 두번째는 \r을 처리 ‌‌‌ ‌‌‌if (input == 'Y' || input == 'y') { ‌‌‌‌System.out.println("게임을 종료합니다."); ‌‌‌‌quit = !quit; ‌‌‌} ‌‌‌System.in.skip(2);//입력값을 지워줌 ‌‌} } }

 

[ 예제 2 ] 0점에서 100점 사이의 값을 받고 배열에 입력하기

package jun12; import java.util.Arrays; import java.util.Scanner; public class While04 { public static void main(String[] args) { ‌‌int[] score = new int[5]; ‌‌Scanner sc = new Scanner(System.in); ‌‌for (int i = 0; i < score.length; i++) { ‌‌‌System.out.print(i + 1 + "번째 인원의 점수를 입력 : "); ‌‌‌int input = sc.nextInt(); ‌‌‌while (!(input >= 0 && input <= 100)) { ‌‌‌‌System.out.print("다시 입력해주세요 : "); ‌‌‌‌input = sc.nextInt(); ‌‌‌} ‌‌‌// 배열에 점수 입력해주세요. ‌‌‌score[i] = input; ‌‌} ‌‌// 출력 ‌‌System.out.println(Arrays.toString(score)); ‌‌sc.close(); } }

 

03. do~while문

  • 명령 문장 실행 후 조건식 검사
  • while문과 순서가 반대로 실행
  • 값이 false가 나와서 1번은 값이 출력됨

[ 기본 ]

int num = 1; do { ​​​​System.out.println("실행합니다.(do~while)"); // 명령문장 } while (num < 0); // 조건식 // 실행합니다.(do~while)

 

[ 활용 ] while문과 do~while문의 차이

package jun12; public class DoWhile02 { public static void main(String[] args) { ‌‌boolean check = true; ‌‌ ‌‌do { ‌‌‌System.out.println("do~while 출력문 " + check); ‌‌} while (check = false);// 1번 출력 됨 ‌‌ ‌‌ ‌‌while (check = false) { ‌‌‌System.out.println("while 출력문 " + check);//출력 안됨 ‌‌} } }// do~while 출력문 true

 

04. break문

  • 반복문인 for문, while문, do-while문, switch문의 실행을 중지할 때 사용
  • 반복문이 중첩되어 있을 경우 가장 가까운 반복문만 종료
  • 원하는 반복문을 종료시키려면 '라벨' 사용 (ex. break 라벨;)
    (Label : break나 continue가 실행할 반복문의 위위치를 이름으로 지정)

[ 기본 ]

for (int i = 1; i <= 10; i++) { ​​​​if (i == 5) { ​​​​​​​​break;//뒤에 코드가 오면 실행 안됨 ​​​​} ​​​​System.out.print(i);// 1234

 

[ 예제 ] 2 x i 가 10보다 작을 경우만 출력하기

for (int i = 1; i < 10; i++) { ​​​​if (i * 2 >= 10) { ​​​​​​​​break; ​​​​} ​​​​System.out.println("2 x " + i + " = " + 2 * i); } /* 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 */

 

[ 활용 ] label 이용

A: for (int i = 0; i < 10; i++) {// label활용 : A라는 이름을 가진 for문 ​​​​for (int j = 0; j < 10; j++) { ​​​​​​​​System.out.print(i + "" + j + " "); ​​​​​​​​if (j == 5) { ​​​​​​​​​​​​break A;// A 반복문 탈출 ​​​​​​​​} ​​​​} }// 00 01 02 03 04 05

 

05. continue문

  • 반복문인 for문, while문, do-while문에서만 사용
  • 블록 내부에서 continue문이 실행되면 이하 실행문 무시하고 다시 반복문으로 이동

 

[ 기본 ]

package jun12; public class Continue { public static void main(String[] args) { ‌‌for (int i = 1; i <= 10; i++) { ‌‌‌System.out.print(i); ‌‌‌if (i == 5) { ‌‌‌‌continue;// 이하 실행문을 무시하고 다시 반복 ‌‌‌} ‌‌‌System.out.print(","); ‌‌} } }// 1,2,3,4,56,7,8,9,10,

 

[ 예제 ] 1에서 10 사이의 수 중 짝수만 출력

for (int i = 1; i <= 10; i++) { if ( i % 2 != 0) { ​​​​​​​​continue;// 이하 실행문을 무시하고 다시 반복 ​​​​} ​​​​System.out.print(i + " "); }// 2 4 6 8 10

 

06. 활용 예제

 

[ Q1 ] {75 95 85 100 50} 오름차순으로 배열하기

 

- 방법 (1)

package jun12; import java.util.Arrays; public class Test01 { public static void main(String[] args) { ‌‌int[] a = { 75, 95, 85, 100, 50 }; ‌‌int temp; ‌‌for (int i = 0; i < a.length; i++) { ‌‌‌for (int j = 0; j < a.length - 1; j++) { ‌‌‌‌if (a[j] > a[j + 1]) { ‌‌‌‌‌temp = a[j]; ‌‌‌‌‌a[j] = a[j + 1]; ‌‌‌‌‌a[j + 1] = temp; ‌‌‌‌} ‌‌‌} ‌‌} ‌‌System.out.println(Arrays.toString(a)); } }// [50, 75, 85, 95, 100]

 

 

- 방법 (2)

package jun12; import java.util.Arrays; public class Test01 { public static void main(String[] args) { ‌‌int[] a = { 75, 95, 50, 85, 100 }; ‌‌int temp; ‌‌while (a[0] > a[1] || a[1] > a[2] || a[2] > a[3] || a[3] > a[4]) { ‌‌‌// 정렬이 안 되어있는 경우를 찾는 식 ‌‌‌for (int j = 0; j < a.length - 1; j++) { ‌‌‌‌if (a[j] > a[j + 1]) { ‌‌‌‌‌temp = a[j]; ‌‌‌‌‌a[j] = a[j + 1]; ‌‌‌‌‌a[j + 1] = temp; ‌‌‌‌} ‌‌‌} ‌‌} ‌‌System.out.println(Arrays.toString(a)); } }// [50, 75, 85, 95, 100]

 

 

[ Q2 ] 어떻게 출력될지 예상하기

package jun12; public class Test02 { public static void main(String[] args) { ‌‌ ‌‌for (int i = 0, j = 0; i <= 5; i++) { //i = 5 j = 15 ‌‌‌j += i; ‌‌‌System.out.print(i); ‌‌‌if (i == 5) { ‌‌‌‌System.out.print(" = "); ‌‌‌‌System.out.print(j); ‌‌‌} else { ‌‌‌‌System.out.print(" + "); ‌‌‌} ‌‌‌ ‌‌} } } // 0 + 1 + 2 + 3 + 4 + 5 = 15 (예상) // 0 + 1 + 2 + 3 + 4 + 5 = 15

 

[ Q3 ] 출력 결과가 00001010이 나오도록 빈칸 채우기

package jun12; public class Test03 { ​​​public static void main(String[] args) { ​​​​​​int[] a = new int[8]; ​​​​​​int i = 0; ​​​​​​int n = 10; ​​​​​​while (1.) { ​​​​​​​​​a[i++] = (2.); ​​​​​​​​​n /= 2; ​​​​​​} ​​​​​​for (i = 7; i >= 0; i--) { ​​​​​​​​​System.out.print(a[i]); ​​​​​​} ​​​} }

- 답 : 1. n > 0     2. n % 2

 

 

[ Q4 ] for문 무한반복하기

package jun12; public class For { public static void main(String[] args) { ‌‌for (int i = 0; i < 10; i++) { ‌‌‌System.out.println("반복합니다"); ‌‌‌i = 0; ‌‌} ‌‌for (int i = 0; i < 10; i--) { ‌‌‌System.out.println("반복합니다"); ‌‌} ‌‌ ‌‌for ( ; ; ) {//계속 무한 반복함 ‌‌‌System.out.println("반복합니다"); ‌‌} } }

 

[ Q5 ] for문에 숫자 없이 10번 반복하게 하기

package jun12; public class For { public static void main(String[] args) { ‌‌for (int i = 'A'; i < 'K'; i++) {// char를 int에 넣음 ‌‌‌System.out.println("반복합니다"); ‌‌} } }

 

[ Q6 ] 10 이하로 짝수만 출력

package jun12; public class Test06 { public static void main(String[] args) { ‌‌for (int i = 1; i <= 10; i++) { ‌‌‌if (i%2 == 0) { ‌‌‌‌System.out.println(i); ‌‌‌} ‌‌} } } /* 2 4 6 8 10 */

 

[ Q7 ] 3x3 배열에 1~9까지 숫자 랜덤하게 입력하기

 

- 방법 (1)

package jun12; import java.util.Arrays; public class Sam { public static void main(String[] args) { ‌‌int[][] sam = new int[3][3]; ‌‌/* * [0,0] [0,1] [0,2] * [1,0] [1,1] [1,2] * [2,0] [2,1] [2,2] */ ‌‌for (int i = 0; i < sam.length; i++) { ‌‌‌for (int j = 0; j < sam[i].length; j++) { ‌‌‌‌int temp = (int) (Math.random() * 9) + 1; ‌‌‌‌System.out.println("뽑은 숫자 : " + temp); ‌‌‌‌// 검사 for문 sam[1][0] == temp; ‌‌‌‌boolean check = false; ‌‌‌‌A: for (int k = 0; k < sam.length; k++) { ‌‌‌‌‌for (int k2 = 0; k2 < sam.length; k2++) { ‌‌‌‌‌‌if (temp == sam[k][k2]) { ‌‌‌‌‌‌‌check = true;//중복되는게 있음 ‌‌‌‌‌‌‌break A; ‌‌‌‌‌‌} ‌‌‌‌‌} ‌‌‌‌} // 검사 for문 끝 ‌‌‌‌if (check) { ‌‌‌‌‌j--;// 다시 뽑기 ‌‌‌‌} else { ‌‌‌‌‌sam[i][j] = temp;// 입력해주기 ‌‌‌‌} ‌‌‌} ‌‌} ‌‌for (int[] is : sam) { ‌‌‌System.out.println(Arrays.toString(is)); ‌‌} } }

 

- 방법 (2)

package jun12; import java.util.Arrays; public class Sam02 { public static void main(String[] args) { ‌‌ ‌‌int[][] sam = new int[3][3]; ‌‌int[] number = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };//입력숫자 ‌‌ ‌‌//입력숫자에서 랜덤하게 한 숫자를 뽑아 ‌‌//순차 입력하고 뽑힌 입력 숫자는 0으로 바꾸기 ‌‌//입력 숫자 뽑기에서 0이면 다시 뽑기 ‌‌int temp;//index 용도 ‌‌for (int i = 0; i < sam.length; i++) { ‌‌‌for (int j = 0; j < sam.length; j++) { ‌‌‌‌do { ‌‌‌‌‌temp = (int) (Math.random() * 9) ; ‌‌‌‌} while (number[temp] == 0); ‌‌‌‌sam[i][j] = number[temp];//저장하기 ‌‌‌‌number[temp] = 0;//중복 방지하기 위해서 ‌‌‌‌ ‌‌‌}//배열 내부측 ‌‌}//배열 외부측 ‌‌ ‌‌for (int[] is : sam) { ‌‌‌System.out.println(Arrays.toString(is)); ‌‌} } }

 

- 방법 (3)

package jun12; import java.util.Arrays; public class Sam03 { public static void main(String[] args) { ‌‌ ‌‌int[][] sam = new int[3][3]; ‌‌//index를 뽑아서 해당 위치에 1~9 순차적으로 입력하기 ‌‌for (int i = 1; i < 10; i++) {//입력할 숫자 ‌‌‌int r1 = (int) (Math.random() * 3);//0 1 2 ‌‌‌int r2 = (int) (Math.random() * 3);//0 1 2 ‌‌‌if (sam[r1][r2] == 0) { //초기값이 비어있어? ‌‌‌‌sam[r1][r2] = i; ‌‌‌} else { ‌‌‌‌i--;//중복발생으로 다시 뽑기 ‌‌‌} ‌‌} ‌‌for (int[] is : sam) { ‌‌‌System.out.println(Arrays.toString(is)); ‌‌} } }

 

[ Q8 ] 중복 없이 로또 번호 뽑기

 

- 방법 (1)

package jun12; import java.util.Arrays; public class Lotto { public static void main(String[] args) { ‌‌int[] lotto = new int[6];// 1~45 ‌‌for (int i = 0; i < lotto.length; i++) { ‌‌‌lotto[i] = (int) (Math.random() * 45) + 1; ‌‌‌for (int j = 0; j < lotto.length; j++) { ‌‌‌‌if (lotto[j] == lotto[i]) { ‌‌‌‌‌j--; ‌‌‌‌‌break; ‌‌‌‌} ‌‌‌} ‌‌} ‌‌int temp; ‌‌for (int i = 0; i < lotto.length; i++) { ‌‌‌for (int j = 0; j < lotto.length - 1; j++) { ‌‌‌‌if (lotto[j] > lotto[j + 1]) { ‌‌‌‌‌temp = lotto[j]; ‌‌‌‌‌lotto[j] = lotto[j + 1]; ‌‌‌‌‌lotto[j + 1] = temp; ‌‌‌‌} ‌‌‌} ‌‌} ‌‌// print ‌‌System.out.println(Arrays.toString(lotto)); } }

 

- 방법 (2) : set 이용하기

package jun12; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Lotto { public static void main(String[] args) { ‌‌Set<Integer> lotto = new HashSet<Integer>(); ‌‌ ‌‌while (lotto.size() < 6) { ‌‌‌lotto.add( (int) (Math.random() * 45) + 1 ); ‌‌} ‌‌System.out.println(lotto);//출력 ‌‌ ‌‌//정렬하기 ‌‌ArrayList<Integer> lottoSort = new ArrayList<Integer>(lotto); ‌‌Collections.sort(lottoSort); ‌‌System.out.println(lottoSort); } }

 

 

참고자료
신용권, '혼자 공부하는 자바'

댓글