조건문(condition)과 반복문(Loop)

이상해씨·2023년 4월 25일
0

JAVA

목록 보기
8/40

1. 조건문(condition)

1) if 조건문

1-1) if else 문

if (condition){
	expression
} else {
	expression
}

1-2) Short Hand If...Else(Tenary Operator)

variable = (condition) ? expressionTrue :  expressionFalse;
코드를 입력하세요

2) Switch

  • 장점 : if 조건문에 비해 많은 statement를 작성할 수 있다.
switch(expression) {
  case x:
    // code block 1
    break; // 도달시 switch문 벗어남. 나머지 코드는 무시처리됨으로 시간절약.
  case y:
    // code block 2
    break;
  default:
    // code block 3
}


2. 반복문 (Loop)

1) While

  • 장점 : 시간절약, 오류감소

1-1) while 조건문

while (condition) {
  expression
}
int i = 0;
while (i < 10) {
  System.out.println(i);
  i++;
}

1-2) do/while 조건문

do {
  expression
}
while (condition);
int i = 0;
do {
  System.out.println(i);
  i++;
}
while (i < 10);

2) For

2-1) For

for (블록실행 전 한번 실행; 블록실행을 위한 조건; 블록실행 후 매 번(time) 실행) {
  // block 
}
for (int i = 0; i < 10; i++) {
  System.out.println(i);
}

2-2) Nested Loops

  • outer Loop 안에 inner Loop
  • inner Loop가 outer Loop 횟수만큼 반복
// Outer loop
for (int i = 1; i <= 2; i++) {
  System.out.println("Outer: " + i); // Executes 2 times
  
  // Inner loop
  for (int j = 1; j <= 3; j++) {
    System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
  }
} 
  • 출력값
Outer: 1
 Inner: 1
 Inner: 2
 Inner: 3
Outer: 2
 Inner: 1
 Inner: 2
 Inner: 3

2-3) For - Each Loop

  • 배열 (array) 의 요소(element) 를 추출하는데 사용.
  • 메모리 크기를 미리 지정해주지 않아도 됨.
for (type variableName : arrayName) {
  // block
}
  • 예시
String[] fruit = {"사과", "바나나", "오렌지", "키위"};

for (String i : fruit) {
  System.out.println(i);
}

3) break / continue

3-1) break

  • Loop에서 벗어날 수 있는 명령어
for (int i = 0; i < 5; i++) {
  if (i == 3) {
    break;
  }
  System.out.println(i);
}
// 0부터 4까지 1씩 증가하면서 block를 실행하다가, i가 3이되면 break 실헹하여 Loop 중단.

3-2) continue

  • 루프에서 하나
public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      if (i == 5) {
        continue;
      }
      System.out.println(i);
    }  
  }
}
// i가 5일 때 block 무시하고 진행 
  • 출력값
0
1
2
3
4
6
7
8
9


참고

profile
공부에는 끝이 없다

0개의 댓글