ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมพิมพ์รูปแบบที่น่าสนใจ (Interesting Pattern)
เราจะได้รับครึ่งหนึ่งของความกว้างของรูปแบบ งานคือพิมพ์รูปแบบที่คล้ายกันตามความกว้างที่กำหนด โดยส่วนซ้ายและขวาเป็นภาพกระจกของกัน
ตัวอย่างโค้ด
#include <stdio.h>
// พิมพ์รูปแบบที่กำหนด
void print_pattern(int n) {
int i, j;
// พิมพ์ครึ่งบน
for (i = 1; i <= n; i++) {
for (j = 1; j <= (2 * n); j++) {
// ส่วนซ้าย
if (i < j)
printf(" ");
else
printf("*");
// ส่วนขวา
if (i <= ((2 * n) - j))
printf(" ");
else
printf("*");
}
printf("\n");
}
// พิมพ์ครึ่งล่าง
for (i = 1; i <= n; i++) {
for (j = 1; j <= (2 * n); j++) {
// ส่วนซ้าย
if (i > (n - j + 1))
printf(" ");
else
printf("*");
// ส่วนขวา
if ((i + n) > j)
printf(" ");
else
printf("*");
}
printf("\n");
}
}
int main() {
print_pattern(6);
return 0;
}
ผลลัพธ์
* * ** ** *** *** **** **** ***** ***** ****** ****** ******* ******* ******** ******** ********* ********* ********** ********** *********** *********** ************ ************ ************* ************* ************** ************** *************** *************** **************** **************** *************** *************** ************** ************** ************* ************* ************ ************ *********** *********** ********** ********** ********* ********* ******** ******** ******* ******* ****** ****** ***** ***** **** **** *** *** ** ** * *