Home > Mobile >  What is the purpose of 'flag' in a prime number program?
What is the purpose of 'flag' in a prime number program?

Time:01-21

I saw this code from a website and there wasn't any explanation behind or specifically the purpose of the flag line.

#include <iostream>
using namespace std;

int main()
{
  int n, i, m = 0, flag = 0;
  
  cout << "Input a number: ";
  cin >> n;
  
  m = n / 2;

  for(i = 2; i <= m; i  )
  {  
      if(n % i == 0)  
      {  
          cout << "Input is not a prime number." << endl;  
          flag = 1;
          break;  
      }  
  }  
  if (flag == 0) {
      cout << "Input is a prime number." << endl;
    }
    
  return 0;
}

P.S. It's a rookie question.

CodePudding user response:

The "flag" variable is just a Boolean variable. If the number n is divisible by any number between 2 and n/2 then the program will display "Input is not a prime number" and flag will be set to 1 (then there's also the "break;" to end the cycle since you already proved the number is not prime). When the for ends then it checks if flag is equal to 0, if it is then it means the number is prime, else it won't display anything.

CodePudding user response:

Since that loop can exit for 2 reasons

  • the number is not prime (there is a break statement)
  • once i reaches m (the for loop terminates)

the code after the loop needs to know which exit happened so that it can say that the number is prime if it exited for the second reason. A more canonical way to do it is

 for(i = 2; i <= m; i  )
 {  
    if(n % i == 0)  
    {  
       cout << "Input is not a prime number." << endl;  
       break;  
    }  
 }  
 if (i > m) {
   cout << "Input is a prime number." << endl;
 }

ie look at the loop condition variables and see if the loop exit condition happened

of at least use a bool with a good name

bool not_prime = false;
  •  Tags:  
  • Related