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

พิมพ์รูปดาวแบบเพชร (Diamond Pattern) ด้วยภาษา C

ใช้ nested for loop เพื่อพิมพ์ดาวเป็นรูปเพชร แบ่งเป็น 2 ส่วน: ส่วนบนและส่วนล่าง

ตรรกะส่วนบนของเพชร

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

ตัวอย่าง rows = 5:

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

ตรรกะส่วนล่างของเพชร

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

ตัวอย่าง rows = 5:

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

โปรแกรมเต็ม

#include <stdio.h>
int main() {
    int rows, i, j;
    printf("Enter no of rows: ");
    scanf("%d", &rows);
    // ส่วนบน
    for (j = 1; j <= rows; j++) {
        for (i = 1; i <= rows - j; i++)
            printf(" ");
        for (i = 1; i <= 2*j - 1; i++)
            printf("*");
        printf("\n");
    }
    // ส่วนล่าง
    for (j = 1; j <= rows - 1; j++) {
        for (i = 1; i <= j; i++)
            printf(" ");
        for (i = 1; i <= 2*(rows - j) - 1; i++)
            printf("*");
        printf("\n");
    }
    return 0;
}

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

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