ที่นี่เราจะดูวิธี generate hollow pyramid และ diamond patterns ด้วย C สร้าง solid Pyramid patterns ได้ง่าย เพื่อทำให้ hollow ต้องเพิ่ม tricks นิดหน่อย
Hollow Pyramid
สำหรับ pyramid บรรทัดแรกพิมพ์ดาว 1 ดวง บรรทัดสุดท้ายพิมพ์ n ดาว บรรทัดอื่นพิมพ์ดาว 2 ดวงที่ต้นและท้ายบรรทัด มี blank spaces ระหว่างดาวสองดวง
ตัวอย่างโค้ด
#include <stdio.h> int main() { int n, i, j; printf("Enter number of lines: "); scanf("%d", &n); for(i = 1; i<=n; i++) { for(j = 1; j<=(n-i); j++){ //print the blank spaces before star printf(" "); } if(i == 1 || i == n){ //for the first and last line, print the stars continuously for(j = 1; j<=i; j++) { printf("* "); } } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow printf(" "); } printf("*"); } printf("\n"); } }ผลลัพธ์
Enter number of lines: 20 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Hollow Diamond
สำหรับ diamond บรรทัดแรกและสุดท้ายพิมพ์ดาว 1 ดวง บรรทัดอื่นพิมพ์ดาว 2 ดวงที่ต้นและท้าย มี blank spaces ระหว่างดาว Diamond มี 2 ส่วน: upper half และ lower half Upper half เพิ่ม space count Lower half ลด space count แบ่ง line numbers ด้วย variable mid
ตัวอย่างโค้ด
#include <stdio.h> int main() { int n, i, j, mid; printf("Enter number of lines: "); scanf("%d", &n); if(n %2 == 1) { //when n is odd, increase it by 1 to make it even n++; } mid = (n/2); for(i = 1; i<= mid; i++) { for(j = 1; j<=(mid-i); j++){ //print the blank spaces before star printf(" "); } if(i == 1) { printf("*"); } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++){ //print space to make hollow printf(" "); } printf("*"); } printf("\n"); } for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) { //print the blank spaces before star printf(" "); } if(i == n-1) { printf("*"); } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow printf(" "); } printf("*"); } printf("\n"); }ผลลัพธ์
Enter number of lines: 15 * * * * * * * * * * * * * * * * * * * * * * * *