ที่นี่เราจะดูวิธีสร้างรูปพีระมิดว่าง (hollow pyramid) และรูปเพชรทรงกลมว่าง (hollow diamond patterns) โดยใช้ C++ เราสามารถสร้างรูปพีระมิดทึบ (solid Pyramid patterns) ได้ง่ายมาก เพื่อทำให้ว่าง เราต้องเพิ่มเทคนิคเล็กน้อย
พีระมิดว่าง (Hollow Pyramid)
สำหรับพีระมิดที่บรรทัดแรก จะพิมพ์ดาวหนึ่งดวง และที่บรรทัดสุดท้าย จะพิมพ์ดาว 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; } }
ผลลัพธ์

เพชรทรงกลมว่าง (Hollow Diamond)
สำหรับเพชรทรงกลมที่บรรทัดแรกและบรรทัดสุดท้าย จะพิมพ์ดาวหนึ่งดวง สำหรับบรรทัดอื่นๆ จะพิมพ์ดาวสองดวงที่ตำแหน่งเริ่มต้นและสิ้นสุดของบรรทัด และจะมีช่องว่างระหว่างดาวสองดวงนี้ เพชรทรงกลมมีสองส่วน ส่วนบนและส่วนล่าง ที่ส่วนบนเราต้องเพิ่มจำนวนช่องว่าง และสำหรับส่วนล่าง เราต้องลดจำนวนช่องว่าง ตัวเลขบรรทัดสามารถแบ่งออกเป็นสองส่วนโดยใช้ตัวแปรอีกตัวหนึ่งชื่อ 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; } }
ผลลัพธ์
