티스토리 뷰

[Java] 별 찍기 알고리즘


- 직각삼각형


RightAngle.java


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
package org.elukasoul.triangle;
 
public class RightAngle {
 
    // @Date: 2016.06.07
    // @Developer: 손혁(elukasoul@gmail.com)
    // @Program Info: 중첩 반복문을 통한 별찍기 알고리즘
 
    public static void main(String[] args) {
 
        // 외부 반복분이 1회 반복하는 동안 내부 반복문은 조건만큼 반복한다.
 
        for (int i = 0; i < 5; i++) {
            // 1회 반복할 때마다 몇 번의 반복을 할 것인지 조건식을 세운다.
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            System.out.println();
 
        }
 
    }
 
}
 
cs



Output


1
2
3
4
5
6
 
*
**
***
****
 
cs




- 정삼각형


RegularTriangle.java


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
package org.elukasoul.triangle;
 
public class RegularTriangle {
 
    // @Date: 2016.06.07
    // @Developer: 손혁(elukasoul@gmail.com)
    // @Program Info: 중첩 반복문을 통한 별찍기 알고리즘
 
    public static void main(String[] args) {
 
        for (int i = 0; i < 5; i++) {
 
            // 왼쪽 상단에 빈 공간을 출력하기 위한 반복문
            for (int j = i; j < 5; j++) {
                System.out.print(" ");
            }
            // 정삼각형의 왼쪽 부분을 담당하는 반복문
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            // 정삼각형의 오른쪽 부분을 담당하는 반복문
            for (int j = 0; j < i - 1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
 
    }
 
}
 
cs



Output


1
2
3
4
5
6
     
    *
   ***
  *****
 *******
 
cs




- 다이아몬드


Diamond.java


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package org.elukasoul.triangle;
 
public class Diamond {
 
    // @Date: 2016.06.15
    // @Developer: 손혁(elukasoul@gmail.com)
    // @Program Info: 중첩 반복문을 통한 별찍기 알고리즘
 
    public static void main(String[] args) {
 
        // 상단 정삼각형을 출력하는 반복문
        for (int i = 0; i < 5; i++) {
 
            for (int j = i; j < 5; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            for (int j = 0; j < i - 1; j++) {
                System.out.print("*");
            }
 
            System.out.println();
        }
 
        // 하단 역삼각형을 출력하는 반복문
        for (int i = 0; i < 5; i++) {
 
            for (int j = 0; j < i; j++) {
                System.out.print(" ");
            }
 
            for (int j = i; j < 5; j++) {
                System.out.print("*");
            }
            for (int j = i + 1; j < 5; j++) {
                System.out.print("*");
            }
 
            System.out.println();
        }
 
    }
 
}
 
cs



Output


1
2
3
4
5
6
7
8
9
10
11
     
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
 
cs


Recent Comments