C# Tutorial For Beginners: For And Foreach Loop

Updated: Jan 18

For loop is used mainly if you know the exact number of times you want to loop through a code block. 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 its main use is to loop through elements in an array and collections:



9 views0 comments