Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

พิมพ์รูปสามเหลี่ยมใน Java: Triangle Pattern Printing

การพิมพ์รูปสามเหลี่ยม (Triangle Pattern)

ใช้ Nested Loop: ลูปนอกควบคุมแถว (rows) ลูปในควบคุมช่องว่างและสัญลักษณ์

ตัวอย่างโค้ด

import java.util.Scanner; 

public class Demo { 
    public static void main(String[] args) { 
        Scanner scanner = new Scanner(System.in); 
        System.out.print("กรอกจำนวนแถว: "); 
        int rows = scanner.nextInt(); 
        
        for (int i = 1; i <= rows; i++) { 
            // พิมพ์ช่องว่าง (space) - จำนวนลดลงเรื่อยๆ
            for (int j = rows; j >= i; j--) { 
                System.out.print(" "); 
            } 
            
            // พิมพ์สัญลักษณ์ (^) - จำนวนเพิ่มขึ้นเรื่อยๆ
            for (int j = 1; j <= i; j++) { 
                System.out.print("^ "); 
            } 
            
            System.out.println(); // 換行
        } 
        scanner.close(); 
    } 
}

ตัวอย่าง Input/Output

กรอกจำนวนแถว: 5
     ^ 
    ^ ^ 
   ^ ^ ^ 
  ^ ^ ^ ^ 
 ^ ^ ^ ^ ^

คำอธิบาย

แถว (i)Spaces (rows-i)Symbols (i)Output
141" ^"
232" ^ ^"
323" ^ ^ ^"
414" ^ ^ ^ ^"
505"^ ^ ^ ^ ^"

รูปแบบอื่นๆ

1. Left-aligned Triangle

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

2. Right-aligned Triangle

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

3. Pyramid (Equilateral Triangle)

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

4. Inverted Triangle

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

เคล็ดลับ

  • คิดในแง่ของ row และ column แยก logic ช่องว่างและสัญลักษณ์
  • ใช้ System.out.print() (ไม่ขึ้นบรรทัดใหม่) ภายในลูปใน
  • ใช้ System.out.println() จบแถว
  • ลองเขียนเลข row/col บนกระดาษก่อนเขียนโค้ด