Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Flag Controlled Loop

Flag Controlled Loop


Video Summary: https://youtu.be/zXQKDa5ZoG8


Using the boolean "true" or "false" is referred to as using boolean flags. Boolean flags are often used for control like if statements or while loops as they are often more readable. Consider the example boolean conditions:

 
#include <iostream>
using namespace std;

int main(){
    bool isTrue = true;

    while(isTrue){
        cout << "isTrue is " << isTrue << endl;
        isTrue = !isTrue;
    }

    while(!isTrue){
        cout << "isTrue is " << isTrue << endl;
        isTrue = !isTrue;
    }
}

Note the following from the example:

  1. You do not need to write "isTrue == true" because booleans already carry the value of true or false, which is what control tests for in the first place
  2. When a boolean variable is true, it will output 1, and when it is false it will output 0
  3. The not operator ! is used to check for false, which is equal to "isTrue == false"
  4. You can also use ! to set a boolean to it's opposite value, like on lines 9 and 14

Exercise

In this exercise, you will create a simple registration form requiring an email, password, and confirm password, and perform some field validation.

  1. Create a loop that will repeat whenever the form input is not valid
  2. Set the flag to true at the top of the loop
  3. Prompt the user for the three fields
  4. Check if the email field contains an '@' symbol. If it doesn't, print an error message and set valid to false
  5. Check if the password is more than 5 characters, and if it isn't print an error message and set valid to false
  6. Check if the confirm password field matches password, and if it isn't print an error message and set valid to false
  7. Print "registration successful" if valid stays true and the loop exits

Solution