Lesson #9 - For And Foreach Loop

Updated: Dec 13, 2020

For loop is used mainly if you know the exact number of times you want to loop through a block of code. When using the ‘for’ loop, it created with default values as seen in the following example:

We can see that there are three main statements in this loop:

  1. Statement 1 (int i = 0) - Executed only one time before the start of the execution of the code block.

  2. Statement 2 (i < length) - Defines the condition that should be met before executing the code block.

  3. Statement 3 (i++) - Executed per iteration after the code block has been executed and until the condition ends the cycle.

Another example

The foreach loop

The foreach loop is unique as it main use is to loop through elements in an array and collections:



2 views0 comments