Hot Posts

For loops

Format:

for (initialization; termination; increment) {
    statement(s)
}
  • initialization : initializes the loop; executes once at the beginning.
  • when termination expression evaluates to false, the loop terminates.
  • increment : is invoked after each iteration through the loop.

The order of execution:

  • the variable is initialized then
  • it is checked to see if the expression is true,
  • if true the statements are executed,
  • then the variable is incremented,
  • then expression is tested,
  • if true the statements are executed…

[initialized, tested, executed, incremented, tested, executed, incremented…]

      for(int x=0; x<5; x++)
      for(int x=0; x<5; ++x)

0 to 4, using a post- or pre-increment does not affect the number of loops.

     for(int x=0; x<=5; x++)

0 to 5, using = includes the number.

     for(int x=5; x>0; x--)

5 to 1, using < or > excludes the number.

Invalid

     for(int x = 0, int z = 0 ; x < 10; x++){}

Cannot declare a second variable inside a for loop initialisation.

Correct

     for(int x = 0, z = 0 ; x < 10; x++){}

But you can initialise another variable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: