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

การพิมพ์รูปแบบตัวเลข (Number Patterns) ในภาษา C: พีระมิด, สามเหลี่ยม


หลักการพิมพ์ Pattern ด้วย Loop

ใช้ **Nested For Loops**:

  • Outer Loop: ควบคุม **แถว (Rows)**
  • Inner Loop 1: พิมพ์ **Space** (สำหรับจัดกึ่งกลาง)
  • Inner Loop 2: พิมพ์ **Pattern** (ตัวเลข/ดาว/อักขระ)

ตัวอย่างที่ 1: พีระมิดดาว (Pyramid of Stars)

#include <stdio.h>

int main() {
    int n, i, j, space;
    
    printf("Enter number of rows: ");
    scanf("%d", &n);
    
    for (i = 1; i <= n; i++) {
        // พิมพ์ Space นำหน้า
        for (space = 1; space <= n - i; space++)
            printf("  "); // 2 spaces
        
        // พิมพ์ดาว
        for (j = 1; j <= 2 * i - 1; j++)
            printf("* ");
        
        printf("\n");
    }
    return 0;
}

ผลลัพธ์ (n=5):

        * 
      * * * 
    * * * * * 
  * * * * * * * 
* * * * * * * * * 

ตัวอย่างที่ 2: สามเหลี่ยมมุมฉากตัวเลข (Right Triangle Numbers)

#include <stdio.h>

int main() {
    int rows, i, j;
    
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= i; j++)
            printf("%d", j);
        printf("\n");
    }
    return 0;
}

ผลลัพธ์ (rows=5):

1
12
123
1234
12345

Pattern อื่นๆ ที่นิยม

Inverted Pyramid (พีระมิดกลับ)


for (i = n; i >= 1; i--) {
    for (space = 1; space <= n - i; space++) printf("  ");
    for (j = 1; j <= 2 * i - 1; j++) printf("* ");
    printf("\n");
}

Number Pyramid (พีระมิดตัวเลข)


for (i = 1; i <= n; i++) {
    for (space = 1; space <= n - i; space++) printf("  ");
    for (j = 1; j <= i; j++) printf("%d ", j);
    for (j = i - 1; j >= 1; j--) printf("%d ", j);
    printf("\n");
}

Output (n=4):

      1 
    1 2 1 
  1 2 3 2 1 
1 2 3 4 3 2 1 

Floyd's Triangle


int num = 1;
for (i = 1; i <= n; i++) {
    for (j = 1; j <= i; j++)
        printf("%d ", num++);
    printf("\n");
}

Output (n=4):

1 
2 3 
4 5 6 
7 8 9 10 

เคล็ดลับการออกแบบ Pattern

  1. วิเคราะห์ความสัมพันธ์ระหว่าง Row (i) และ Column (j)
  2. หา Formula: จำนวน Space, จำนวน Pattern ต่อ Row
  3. ทดสอบด้วย n เล็ก (3-4) ก่อน
  4. ใช้ Variable Name ที่มีความหมาย (row, col, space, star)