You are here

Understanding Iteration in General - for

10 February, 2015 - 12:09

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 test expression 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 fowcharting. 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 fag done once
  • Test expression
  • 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.