You are here

An Example

10 February, 2015 - 11:12

Example 14.1: C++ source code: while

loop response = 'y'; while (loop response == 'y')   {   cout « "\nWhat is your age? ";   cin » age user;   cout « "\nWhat is your friend's age? ";   cin  _ age_friend;  cout  _ "nnTogether your ages add up to: ";  cout  _ (age_user + age_friend);  cout  _ "nnDo you want to do it again? y or n ";  cin  _ loop_response;  }

The four attributes of a test before loop are present. The initialization of the flag. The test is the equality relational comparison of the value in the flag variable to the lower case character of y. The action part consists of the 6 lines that prompt for data and then displays the total of the two ages. The update of the flag is the displaying the question and getting the answer for the variable loop response.

This type of loop control is called an event controlled loop. The flag updating is an event where someone decides if they want the loop to execute again.

Using indentation with the alignment of the loop actions and flag update is normal industry practice within the C++ community.