# 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.

 `// C++ program to check if given array is has ` `// any even number ` `#include ` `using` `namespace` `std; ` ` `  `bool` `checkIfAnyEven(``int` `arr[], ``int` `n) ` `{ ` `    ``bool` `flag = ``false``; ` `    ``for` `(``int` `i=0; i

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.

 `// C++ implementation to show the use of flag variable ` `#include ` `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; ` `} `

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.

9

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.