Loop, Infinite loop, and flag
Debug > more bug > repeat
Last updated
Was this helpful?
Was this helpful?
int main (){
for(int i =1;i<=10;i++) {
cout << "Doing this for "<< i <<" round"<<endl;
}
}while(1){ // alway true
// task
}for(;;){ // alway true
// task
}// 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;
} #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;
}