เราจะมาดูวิธีการสร้างรูปแบบพีระมิดและเพชรแบบกลวงโดยใช้ C++ เราสามารถสร้างรูปแบบพีระมิดที่เป็นของแข็งได้ง่ายมาก เราต้องเพิ่มลูกเล่นบางอย่างเพื่อให้ดูกลวงๆ
พีระมิดกลวง
สำหรับพีระมิดที่บรรทัดแรก จะพิมพ์ดาวหนึ่งดวง และบรรทัดสุดท้ายจะพิมพ์ดาวจำนวน n ดวง สำหรับบรรทัดอื่นๆ จะพิมพ์ดาวสองดวงตรงจุดเริ่มต้นและจุดสิ้นสุดของบรรทัด และจะมีช่องว่างระหว่างจุดเริ่มต้นทั้งสองนี้
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int n, i, j;
cout << "Enter number of lines: ";
cin >> n;
for(i = 1; i<=n; i++) {
for(j = 1; j<=(n-i); j++) { //print the blank spaces before star
cout << " ";
}
if(i == 1 || i == n) { //for the first and last line, print the stars continuously
for(j = 1; j<=i; j++) {
cout << "* ";
}
}else{
cout << "*"; //in each line star at start and end position
for(j = 1; j<=2*i-3; j++) { //print space to make hollow
cout << " ";
}
cout << "*";
}
cout << endl;
}
} ผลลัพธ์

เพชรกลวง
สำหรับเพชรเส้นแรกและเส้นสุดท้ายจะพิมพ์ดาวหนึ่งดวง สำหรับบรรทัดอื่นๆ จะพิมพ์ดาวสองดวงตรงจุดเริ่มต้นและจุดสิ้นสุดของบรรทัด และจะมีช่องว่างระหว่างการเริ่มต้นทั้งสอง เพชรมีสองส่วน ครึ่งบนและครึ่งล่าง ที่ครึ่งบนเราต้องเพิ่มจำนวนเนื้อที่ และสำหรับครึ่งล่าง เราต้องลดจำนวนเนื้อที่ลง ในที่นี้หมายเลขบรรทัดสามารถแบ่งออกเป็นสองส่วนโดยใช้ตัวแปรอื่นที่เรียกว่า mid
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int n, i, j, mid;
cout << "Enter number of lines: ";
cin >> 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
cout << " ";
}
if(i == 1) {
cout << "*";
}else{
cout << "*"; //in each line star at start and end position
for(j = 1; j<=2*i-3; j++) { //print space to make hollow
cout << " ";
}
cout << "*";
}
cout << endl;
}
for(i = mid+1; i<n; i++) {
for(j = 1; j<=i-mid; j++) { //print the blank spaces before star
cout << " ";
}
if(i == n-1) {
cout << "*";
}else{
cout << "*"; //in each line star at start and end position
for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow
cout << " ";
}
cout << "*";
}
cout << endl;
}
} ผลลัพธ์
