ที่นี่เราจะมาดูวิธีการสร้างรูปแบบพีระมิดกลวงและเพชรโดยใช้ C เราสามารถสร้างรูปแบบพีระมิดที่เป็นของแข็งได้ง่ายมาก เราต้องเพิ่มลูกเล่นบางอย่างเพื่อให้ดูกลวงๆ
พีระมิดกลวง
สำหรับพีระมิดที่บรรทัดแรก จะพิมพ์ดาวหนึ่งดวง และบรรทัดสุดท้ายจะพิมพ์ดาวจำนวน n ดวง สำหรับบรรทัดอื่นๆ จะพิมพ์ดาวสองดวงตรงจุดเริ่มต้นและจุดสิ้นสุดของบรรทัด และจะมีช่องว่างระหว่างจุดเริ่มต้นทั้งสองนี้
โค้ดตัวอย่าง
#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 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
เพชรกลวง
สำหรับเพชรเส้นแรกและเส้นสุดท้ายจะพิมพ์ดาวหนึ่งดวง สำหรับบรรทัดอื่นๆ จะพิมพ์ดาวสองดวงตรงจุดเริ่มต้นและจุดสิ้นสุดของบรรทัด และจะมีช่องว่างระหว่างจุดเริ่มต้นทั้งสองนี้ เพชรมีสองส่วน ครึ่งบนและครึ่งล่าง ที่ครึ่งบนเราต้องเพิ่มจำนวนช่องว่าง และสำหรับครึ่งล่าง เราต้องลดจำนวนช่องว่าง ในที่นี้หมายเลขบรรทัดสามารถแบ่งออกเป็นสองส่วนโดยใช้ตัวแปรอื่นที่เรียกว่า 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 * * * * * * * * * * * * * * * * * * * * * * * * * * * *