Skip to main content
Engineering LibreTexts

8.1: For Loop

  • Page ID
    29076
  • Introduction to Test Before Loops

    We have discussed the while loop in the previous module. We now turn out attention to the for loop. The for loop is a great way to process a loop for a finite number of times, meaning that you can programmatically determine how many times you need to loop.

    Understanding Iteration in General - for

    In most programming languages the for loop is used exclusively for counting; that is to repeat a loop action as it either counts up or counts down. There is a starting value and a stopping value. The question that controls the loop is a condition that compares the starting value to the stopping value. This expression is a Boolean expression and is usually using the relational operators of either less than (for counting up) or greater than (for counting down). The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the for loop (counting up) is as follows:

    for
      initialization of the starting value
      starting value is less than the stopping value
      some statements or action
      some statements or action
      some statements or action
      increment the starting value
    

    It might be best to understand the for loop by understanding a while loop acting like a counting loop. Let's consider;

    initialization of the starting value
    while the starting value is less than the stopping value
      some statements or action
      some statements or action
      some statements or action
      increment the starting value
    

    Within the for control structure there are four attributes to a properly working loop. They are:

    • Initializing the flag – done once
    • Test condition
    • Action or actions
    • Update of the flag

    The initialization of the flag is not technically part of the while control structure, but it is usually part of the for control structure. The English phrasing is, "For x is 1; x less than 3; do the following actions; increment x; loop back to the test expression". This is doing the action on the true. When the test expression is false, you stop the loop and go on with the next item in the program. Notice, because this is a test before loop the action might not happen. It is called a test before loop because the test comes before the action. It is also sometimes called a pre-test loop, meaning the test is pre (or Latin for before) the action and update.

    The for Structure within C++

    Syntax

    The syntax of the for loop control structure within the C++ programming language is:

    for (initializations; condition; updates)
    {
      statement;
      statement;
      statement;
    }
    

    The initializations, test expression and updates are within the parentheses (each separated by a semi-colon), but this is not a function call. The parentheses are part of the control structure. Additionally, there is not a semicolon after the parenthesis following the expression.

    An Example

    C++ source code: for
    for (counter = 0; counter < 5; counter++)
    {
      cout << "Counter is now set to: " << counter << endl;
    }
    

    The four attributes of a test before loop (remember the for loop is one example of a test before loop) are present.

    • The initialization of the counter variable (this is our flag) to a value of 0. THIS ONLY HAPENS ON THE VERY FIRST ITERATION OF THE LOOP
    • The test is the less than relational comparison of the value in the counter variable to the constant value of 5.
    • The cout statement is output
    • The update of the counter variable is done with the increment operator.

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

    Infinite Loops

    At this point it's worth mentioning that good programming always provides for a method to insure that the loop question will eventually be false so that the loop will stop executing and the program continues with the next line of code. However, if this does not happen then the program is in an infinite loop. Infinite loops are a bad thing. Consider the following code:

    C++ source code: infinite loop
    for (counter = 0; counter < 5;)
    {
      cout << "\nI love ice cream!";
    }
    

    The programmer assigned a value to the counter variable (our flag) during the initialization step which is correct. However, he forgot to update the flag (the update step is missing). Every time the test expression is asked it will always be true. Thus, an infinite loop because the programmer did not provide a way to exit the loop (he forgot to update the flag).

    Multiple Items in the Initialization and Update

    The following shows the use of the sequence operator to separate the multiple initializations and multiple updates. This is not available in most languages, thus is more unique to the C++ programming language.

    C++ source code: for with multiple initializations and updates
    for (x = 0, y = 10; x < 10; x++, y--)
    {
      cout << "The product of x * y is: " << x * y << endl;
    }
    

    Counting Loop Conversion - a while into a for

    Below is a color coded the conversion of a while loop that displays a message exactly three times (which is a counting loop) into a for loop using C++ programming language syntax. The four loop attributes are color highlighted as follows:

    blue is the initialize<
    orange is the test
    green is the action
    red is the update
    
    counter = 0;
    while (counter < 3)
    {
         cout << "Please wrote good code" << endl;
         counter++;
     }
     
    // The for loop that does this same thing is:
     for (counter = 0; counter < 3; counter++)
     {
        cout << "Please wrote good code" << endl;
     }
    

    Definitions

    for
    A test before iteration control structure typically used for counting.

    Adapted from:
    "For Loop" by Kenneth Busbee, Download for free at http://cnx.org/contents/303800f3-07f...93e8948c5@22.2 is licensed under CC BY 4.0