ปัญหา
ตรรกะในภาษาซีในการพิมพ์ตัวเลขในรูปแบบต่างๆ เช่น พีระมิด สามเหลี่ยมมุมฉาก คืออะไร
วิธีแก้ปัญหา
หากต้องการพิมพ์ตัวเลขหรือสัญลักษณ์ในรูปแบบต่างๆ เราสามารถใช้ for วนซ้ำในโค้ดได้
ตัวอย่าง1
ต่อไปนี้เป็นโปรแกรม C เพื่อพิมพ์พีระมิด -
#include<stdio.h>
int main(){
int n;
printf("Enter number of lines: ");
scanf("%d", &n);
printf("\n");
// loop for line number of lines
for(int i = 1; i <= n; i++){
// loop to print leading spaces in each line
for(int space = 0; space <= n - i; space++){
printf(" ");
}
// loop to print *
for(int j = 1; j <= i * 2 - 1; j++){
printf(" * ");
}
printf("\n");
}
return 0;
} ผลลัพธ์
Enter number of lines: 8 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
ตัวอย่างที่ 2
ต่อไปนี้เป็นโปรแกรมแสดงตัวเลขในรูปสามเหลี่ยมมุมฉาก (แบบ) −
#include <stdio.h>
void main(){
int i,j,rows;
printf("Input number of rows : ");
scanf("%d",&rows);
for(i=1;i<=rows;i++){
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
} ผลลัพธ์
Input number of rows : 10 1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910