250x250
Recent Posts
Notice
Today
Total
«   2025/05   »
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
Archives
관리 메뉴

코딩알파

[Java] for문 별 피라미드 만들기 (이중for문) 본문

JAVA공부

[Java] for문 별 피라미드 만들기 (이중for문)

코딩알파 2021. 9. 29. 14:52
728x90
직각삼각형

 

 
for(int i =1; i<=5; i++) {
            for(int j=1; j<=i; j++) {
                System.out.print("*");
            }
            System.out.println();
         }
cs

 

 
*
**
***
****
*****
cs

 

가장 간단한 별 피라미드 만들기

이중 for문을 이용해서 차례대로 별을 찍으면 된다.

 

직각삼각형 (반대로)

 

 
    for(int i=1; i<=5; i++) {
             for(int j=1; j<=5-i; j++) {
                 System.out.print(" ");
             }
             for(int k=1; k<=i; k++) {
                 System.out.print("*");
             }
             System.out.println();
         }
cs

 

 
    *
   **
  ***
 ****
*****
cs

 

여기선 for문 하나 더 추가되었다.

2중 for문에서 공백 자리를 만들어주고 추가된 for문에서 * 표시를 해준다.

 

직각삼각형 (뒤집기)

 

 
 for(int i = 5; i>=1; i--) {
             for(int j=1; j<=i; j++) {
                 System.out.print("*");
             }
             System.out.println();
         }
cs

 

 
*****
****
***
**
*
cs

 

처음 직각삼각형에 반대로만 해주면 된다.

 

직각삼각형(반대로)

 

 
for(int i=5; i>=1; i--) {
            for(int j=1; j<=5-i; j++) {
                System.out.print(" ");
            }
            for(int k=1; k<=i; k++) {
                System.out.print("*");
            }
            System.out.println();
            
        }
cs

 

 
*****
 ****
  ***
   **
    *
cs
728x90
Comments