Loop, Infinite loop, and flag
Debug > more bug > repeat
Loop
การเขียนโปรแกรมให้ทำซ้ำจำเป็นจะต้องใช้คำสั่งประเภท Loop ซึ่งมีสองประเภทคือ While และ forเพื่อทำซ้ำ
while loop
เป็นการทำซ้ำแบบทำไปเรื่อยๆจนกว่าจะผิดเงื่อนไข เมื่อผิดเงื่อนไขโปรแกรมจะหยุดจากการทำซ้ำและไปยังคำสั่งที่มีอยู่ถัดไป
#include<iostream>
using namespace std;
int main () {
int A = 0;
while (A<10) {
cout << "Doing this for "<< ++A <<" round"<<endl;
}
cout << "Program end"<<endl;
return 0;
}
for loop
เป็นการทำซ้ำแบบจำกัดรอบ โดยสามารถกำหนดได้ว่าจะทำทั้งหมดกี่รอบ และสามารถนำไปประยุกต์ในการจัดการตัวแปรประเภทอาร์เรย์ได้ง่าย
int main (){
for(int i =1;i<=10;i++) {
cout << "Doing this for "<< i <<" round"<<endl;
}
}
Infinite loop
แต่ถ้าเราต้องการให้ทำซ้ำไปเรื่อยๆ โดยไม่หยุดต้องทำยังไง? เพียงกำหนดให้ loop ทำงานด้วยเงื่อนไขที่ถูกต้องตลอดโปรแกรมของเราก็จะทำงานไปเรื่อยๆโดยไม่หยุดแล้ว
while loop
while(1){ // alway true
// task
}
for loop
for(;;){ // alway true
// task
}
แล้วทั้งสองแบบแตกต่างกันอย่างไร ในภาษา C/C++
คำตอบ ไม่ต่างกัน ทั้งสองแบบสามารถทำงานได้ด้วยความเร็วเท่ากัน คอมไพล์เลอร์ใช้เวลาคอมไพล์เท่ากัน เวลาประมวลผลการทำงานเท่ากัน
Flag
Flag คืออะไร Flag คือส่วนหนึ่งของโปรแกรมที่ทำหน้าที่ส่งสัญญาณบอกว่าโปรแกรมนั้นได้ผ่านเงื่อนไขนั้นแล้วหรือยัง เช่นโปรแกรมตรวจสอบเลขเฉพาะ
// C++ implementation to show the use of flag variable
#include <iostream>
using namespace std;
// Function to return true if n is prime
bool isPrime(int n)
{
bool flag = true;
// Corner case
if (n <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < n; i++) {
// Set flag to false and break out of the loop
// if the condition is not satisfied
if (n % i == 0) {
flag = false;
break;
}
}
// flag variable here can tell whether the previous loop
// broke without completion or it completed the execution
// satisfying all the conditions
return flag;
}
// Driver code
int main()
{
if(isPrime(13))
cout << "PRIME";
else
cout << "NOT A PRIME";
return 0;
}
อ้างอิง : geeksforgeeks
จากโปรแกรมด้านบนจะเห็นได้ว่าตัวแปร flag จะเป็นประเภท bool เพื่อเก็บค่าที่แสดงว่า true หรือ false เท่านั้น เมื่อโปรแกรมได้รับค่าตัวเลขที่เป็นจำนวนเฉพาะค่า flag ก็จะเป็น true และส่งค่ากลับไปยัง
เพื่อนำค่าไปใช้ต่อ
ไม่เพียงแค่จะใช้เขียนในโปรแกรมปกติเท่านั้น flag ยังสามารถใช้หยุด loop ได้ด้วยเมื่อใช้ Infinite loop เช่น
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
bool flag = true; // flag varieble
if (argc != 2) {
cout<<"Please enter argrument in number"<<endl;
exit(1);
}
cout << "Program start" << endl;
int k = atoi(argv[1]); // starting integer
while(flag){
if (k%100==0){
flag=!flag; // condition met, flag change
}
cout << k << endl;
k++;
}
cout << "Program stop" << endl;
}
จากด้านบนจะเห็นว่าโปรแกรมจะนับจาก k ไปจนกว่าจะหารเลข 100 ลงตัวแล้วจะหยุดลง โดยมีตัวแปร flag เป็นตัวควบคุมการทำงานของโปรแกรม
Last updated
Was this helpful?