1. ข้อความสั่ง for (ต่อ)
1. ข้อความสั่ง for (ต่อ)
ตัวอย่าง 4.8 รับค่าตัวเลข และแสดงดอกจัน
#include <stdio.h>
int main()
{
int i, j, num;
printf("Enter number : ");
scanf("%d", &num);
for(i = 1;i <= num; i++) {
for(j = 1; j <= i; j++){
printf("*");
}
printf("\n");
}
}
ผลลัพธ์ของโปรแกรม
ตัวอย่าง 4.9 รับค่าตัวเลข และแสดงดอกจัน
#include <stdio.h>
int main()
{
int i, j, num;
printf("Enter number : ");
scanf("%d", &num);
for(i = num; i >= 1; i--) {
for(j = 1; j <= i; j++){
printf("*");
}
printf("\n");
}
}
ผลลัพธ์ของโปรแกรม
ตัวอย่าง 4.10 โปรแกรมแสดงตัวเลข 1 – 9 เป็นรูปสามเหลี่ยม แบบหลังคา
#include <stdio.h>
int main()
{
int loop = 9;
int i;
int j;
int sloop;
for(i = 1; i <= loop; i++){
sloop = loop - i;
for(j = 1; j <= sloop; j++ ){
printf(" ");
}
printf("%d", i);
if(i == 1){
printf("\n");
continue;
}
sloop = (i * 2) - 1;
for(j = 2; j < sloop; j++ ){
printf(" ");
}
printf("%d\n", i);
}
}
ผลลัพธ์ของโปรแกรม
ตัวอย่าง 4.11 โปรแกรมแสดงตัวเลขเป็นรูปสามเหลี่ยมด้วยลูป for แบบกลับหัวลง
#include<stdio.h>
int main()
{
int loop = 9;
int i;
int j;
for(i = 1; i <= loop; i++){
for(j = 1; j<= i; j++){
printf(" ");
}
for(j = 1; j <= (loop-i)+1; j++){
printf("%d", j);
}
for(j = loop-i; j >= 1; j--){
printf("%d", j);
}
printf("\n");
}
}
ผลลัพธ์ของโปรแกรม
จัดทำโดย นางสาวทิพย์สุคนธ์ พันธ์กิ่ง กลุ่มสาระการเรียนรู้วิทยาศาสตร์และเทคโนโลยี
โรงเรียนบุญวัฒนา สำนักงานเขตพื้นที่การศึกษามัธยมศึกษานครราชสีมา