Use of FLAG in programming

Flag variable is used as a signal in programming to let the program know that a certain condition has met. It usually acts as a boolean variable indicating a condition to be either true or false.

Example 1 : Check if an array has any even number.

Input : arr[] = {1, 3, 7, 5}
Output : No
All numbers are odd.

Input : arr[] = {1, 2, 7, 5}
Output : Yes
There is one even number in the array.

We initialize a flag variable as false, then traverse the array. As soon as we find an even element, we set flag as true and break the loop. Finally we return flag.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to check if given array is has
// any even number
#include <iostream>
using namespace std;
  
bool checkIfAnyEven(int arr[], int n)
{
    bool flag = false;
    for (int i=0; i<n; i++)
    {
        if (arr[i] % 2 == 0)
        {
            flag = true;
             break;
        }
    }
    return flag;
}
  
int main()
{
   int arr[] = {1, 3, 2, 5, 6, 7}; 
   int n = sizeof(arr)/sizeof(arr[0]);
   if (checkIfAnyEven(arr, n))
     cout << "Yes";
   else
     cout << "No";
}

chevron_right


Output:

Yes

Example 2 : Check if given number is prime or not.

Input : n = 5
Output : Yes

Input : n = 18
Output : No

We initialize a flag variable as true. Then we traverse through all numbers from 2 to n-1. As soon as we find a number that divides n, we set flag as false. Finally we return flag.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

PRIME


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.