[JAVA] 반복문 (loops)

Coastby·2022년 7월 27일
0

JAVA

목록 보기
7/33

규칙적 반복 코드를 단순화하는 문법

while 문

  • while 문 : 반복 횟수가 상황따라 다른 경우에 사용
// ①➝②를 반복(조건식이 거짓이 될 때까지)
while (①조건식) {
  ②반복 내용
}

예제)

public class WhileStatement {
  public static void main(String[] args) {
    // 입력값 받기
    int startNum = Integer.parseInt(args[0]);

    // 카운트 다운 출력
    countDown(startNum);
  }

  public static void countDown(int num) {
    System.out.println("카운트 다운을 시작합니다..");
    while (num >= 0) {
      System.out.printf("%d..\n", num);
      num--;
    }
    System.out.println("발사!!");
  }
}

//입력
5

//출력
카운트 다운을 시작합니다..
5..
4..
3..
2..
1..
0..
발사!!

for 문

  • for 문 : 반복 횟수가 명확할 때
// ⓪초기화 수행 후,
// ①➝②➝③ 반복(거짓이 될 때까지)
for (⓪초기값; ①조건식; ③갱신) {
  ②반복 내용
}

예제)

  • for 문 구조
  • 띄어쓰기로 결과 출력하기
public class ForStatement {
  public static void main(String[] args) {
    // 입력값 받기
    int n = Integer.parseInt(args[0]);

    // 메소드를 통한, 결과 출력
    printNumbers(n);
  }

  // 1부터 N까지, 정수를 출력
  public static void printNumbers(int max) {
    // 출력 시작!
    System.out.println("출력을 시작합니다..");
    
    //반복을 통한, 숫자 출력
    for (int i = 1; i <= max; i++) {
      System.out.printf("%d ", i);
    }
    
    System.out.println("\n끝!!");
  }
}

//출력
출력을 시작합니다..
1 2 3 4 5 6 7!!

break 문

if (조건식) { // 조건식이 참이면
  break;    // 반복문 탈출!
}

continue 문

if (조건식) { // 조건식이 참이면
  continue; // 다음 반복으로 강제 이동!
}

연습문제

구구단 출력하기

public class GuGuDan {
  public static void main(String[] args) {
    // 구구단 출력
    printGuGuDan();
  }
  
  public static void printGuGuDan () {
    for (int i = 2; i <= 9; i++) {
      System.out.printf("%d단\n", i);
      printDan(i);
    }
  }
  
  public static void printDan(int dan) {
    for (int j = 1; j <= 9; j++) {
      int multiple = j * dan;
      System.out.printf("\t%d x %d = %d\n", dan, j, multiple);
    }
  }
}

//출력
22 x 1 = 2
    2 x 2 = 4
       ...
    2 x 9 = 18
...
99 x 1 = 9
       ...
    9 x 9 = 81
profile
훈이야 화이팅

0개의 댓글