큐범
Just do debug
큐범
전체 방문자
오늘
어제
  • 전체보기 (128)
    • 회고 (4)
    • JAVA (16)
      • JAVA 기초 (18)
      • JAVA Algorithm, Datastruct (13)
    • Spring (11)
    • Micro Service Architecture (3)
    • JPA (6)
    • gRPC (4)
    • Network (8)
    • Process (7)
    • Cloud (4)
    • Python (10)
    • Web(vue) (2)
    • UMC (1)
    • DB (9)
    • CS (1)
    • Clean Code (1)
    • TDD (9)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

인기 글

최근 댓글

최근 글

hELLO · Designed By 정상우.
큐범

Just do debug

JAVA/JAVA 기초

[JAVA 기초] 반복문(for문)

2021. 7. 20. 13:15

for문

for문은 반복 횟수를 알고 있을 때 적합하다. 구조가 조금 복잡하긴 하나, 직관적이라 오히려 이해도 측면에서는 다른 반복문 보다 우수하다.

for(초기화; 조건식; 증감식)

초기화

반복문에 사용될 변수를 초기화 하는 부분이며 처음에 한번만 수행한다.

조건식

조건식의 참(true)이면 반복을 계속하고 거짓(false)라면 반복을 중단하고 for문을 벗어난다.

증감식

반복문을 제어하는 변수의 값을 증가 또는 감소시키는 식이다.

 

public static void main(String[] args) {
		for(int i=1; i<=5; i++) {
			System.out.println(i);
		}
		for(int i=1; i<=5; i++) {
			System.out.print(i);
		}
	}
//결과
1
2
3
4
5
12345
public static void main(String[] args) {
		int sum=0;
		
		for(int i=1; i<=10; i++) {
			sum += i;
			System.out.printf("1부터 %2d 까지의 합: 2%d%n", i, sum);
		}
	}
//결과
1부터  1 까지의 합: 21
1부터  2 까지의 합: 23
1부터  3 까지의 합: 26
1부터  4 까지의 합: 210
1부터  5 까지의 합: 215
1부터  6 까지의 합: 221
1부터  7 까지의 합: 228
1부터  8 까지의 합: 236
1부터  9 까지의 합: 245
1부터 10 까지의 합: 255
public static void main(String[] args) {
		for(int i=1, j=10; i<=10; i++,j--) {
			System.out.printf("%d \t %d%n", i, j);
		}
	}
//결과
1 	 10
2 	 9
3 	 8
4 	 7
5 	 6
6 	 5
7 	 4
8 	 3
9 	 2
10 	 1
public static void main(String[] args) {
		System.out.println("i \t 2*i \t 2*i-1 \t i*i \t 11-i \t i%3 \t i/3");
		System.out.println("---------------------------------------------------");
		
		for(int i=1; i<=10; i++) {
			System.out.printf("%d \t %d \t %d \t %d \t %d \t %d \t %d%n",
								i, 2*i, 2*i-1, i*i, 11-i, i%3, i/3);
		}
//결과
i 	 2*i 	 2*i-1 	 i*i 	 11-i 	 i%3 	 i/3
---------------------------------------------------
1 	 2 	 1 	 1 	 10 	 1 	 0
2 	 4 	 3 	 4 	 9 	 2 	 0
3 	 6 	 5 	 9 	 8 	 0 	 1
4 	 8 	 7 	 16 	 7 	 1 	 1
5 	 10 	 9 	 25 	 6 	 2 	 1
6 	 12 	 11 	 36 	 5 	 0 	 2
7 	 14 	 13 	 49 	 4 	 1 	 2
8 	 16 	 15 	 64 	 3 	 2 	 2
9 	 18 	 17 	 81 	 2 	 0 	 3
10 	 20 	 19 	 100 	 1 	 1 	 3

중첩 for문

public static void main(String[] args) {
		for(int i=1; i<=5; i++) {
			for(int j=1; j<=10; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
//결과
**********
**********
**********
**********
**********

구구단

public static void main(String[] args) {
		for(int i=2; i<=9; i++) {
			for(int j=1; j<=9; j++) {
				System.out.printf("%d x %d = %d%n", i, j, i*j);
			}
		}
	}
//결과
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
....
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81

3개의 for문 예제

public static void main(String[] args) {
		for(int i=1; i<=3; i++) {
			for(int j=1; j<=3; j++) {
				for(int k=1; k<=3; k++) {
					System.out.println(""+i+j+k);
				}
			}
		}
	}
//결과
111
112
113
121
...
322
323
331
332
333
public static void main(String[] args) {
		for(int i=1; i<=5; i++) {
			for(int j=1; j<=5; j++) {
				System.out.printf("[%d, %d]", i, j);
			}
			System.out.println();
		}
	}
//결과
[1, 1][1, 2][1, 3][1, 4][1, 5]
[2, 1][2, 2][2, 3][2, 4][2, 5]
[3, 1][3, 2][3, 3][3, 4][3, 5]
[4, 1][4, 2][4, 3][4, 4][4, 5]
[5, 1][5, 2][5, 3][5, 4][5, 5]
public static void main(String[] args) {
		for(int i=1; i<=5; i++) {
			for(int j=1; j<=5; j++) {
				if(i==j) {
					System.out.printf("[%d, %d]", i, j);
				}else {
					System.out.printf("%5c", ' ');
				}
			}
			System.out.println();
		}
	}
//결과
[1, 1]                    
     [2, 2]               
          [3, 3]          
               [4, 4]     
                    [5, 5]

향상된 for문

배열과 컬렉션에 저장된 요소에 접근이 더 간편하게 처리할 수 있는 for문이 생겼다.

for(타입 변수명 : 배열 또는 컬렉션){

//반복

 

}

public static void main(String[] args) {
		int [] arr = {10,20,30,40,50};
		int sum = 0;
		
		for(int i=0; i<arr.length; i++) {
			System.out.printf("%d ", arr[i]);
		}
		System.out.println();
	
	
		for(int tmp : arr) {
			System.out.printf("%d ", tmp);
			sum += tmp;
		}
		System.out.println();
		System.out.println("sum="+sum);
	}
//결과
10 20 30 40 50 
10 20 30 40 50 
sum=150

첫번째의 for문에 비해 두번째의 for문이 더 직관적으로도 간단해보이나, 배열이나 컬렉션에 저장된 요소들을 읽어오는 용도로만 사용된다는 제약이 존재한다.

출처 : JAVA의 정석 - (남궁성지음)

    'JAVA/JAVA 기초' 카테고리의 다른 글
    • [JAVA 기초] 배열 (선언, 생성, 길이, 초기화, 활용)
    • [JAVA 기초] 반복문(while)
    • [JAVA 기초] 조건문(switch)
    • [JAVA 기초] 조건문 (if-else, 중첩if)
    큐범
    큐범

    티스토리툴바