for Loops

for (counter = initial-expression; logical-expression; change-counter)
        statement
  • A for loop is executed as follows:
  • The statement repeated by the for loop can also be a compound statement:
  • for (counter = initial-expression; logical-expression; counter-change)
    {
        statement
        statement
        ...
    }
    
  • A real section of code is a little clearer:
    for (i = 1; i <= 10; i++)
    {
        statement
        statement
        ...
    }
    
  • In the for loop above, how many times will the statements be repeated?

  • The first part of the for loop, i = 1; initializes the object i to the value 1.

  • The next part, i <= 10; contains the logical expression that will be evaluated each time through the loop. The loop will continue until this expression evaluates to false.
  • The last part, i++ increments i by adding 1 to it (it could also have been written as i = i + 1 or i += 1).
  • At the conclusion of the loop, i has the value 11.
  • Typically, the variable i should be of type int, but for loops can be written with floats or doubles, if appropriate.
  • You can change the counter in any way you would like. For instance, you could write a for loop that counts by 5s:
  • for (i = 5; i <= 30; i = i + 5)
        statement
    
  • You can also use a for loop that counts down. How would you do it?
  • Tips on for Loops