Related Articles
Use of FLAG in programming
• Difficulty Level : Easy
• Last Updated : 05 Dec, 2018

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
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up