For loops are used to repeat code a certain number of times. For example, a for loop could be used to repeat an instruction 10 times. For loops are much more useful than that though. For example, they can be used to process items in a list one-by-one (we will learn how to do that later).
Watch the video below and then scroll down to see the sample code.
The for loop is a little more complex than the while loop but at its simplest level it is very easy to set up. The syntax looks like this:
for(<initialise counter>;<condition>;<increment the counter>) { // do something }
Semi-colons separate three important components of the for loop inside the ( and ) brackets. The first part is where a counter is initialised, for example int i=0. The second part is where the condition is specified, for example i<10. The third part is how much to increment the counter by each time the loop runs (each iteration), for example i++ would increment the counter by 1.
For loops are great for using as counters to repeat a section of code a certain amount of times. They are also great for repeating operations on each item in an array (looping through an array) or each character in a string. Below is an example of a for loop.
Sample code
This for loop will start with an integer value of 0 and then keep increasing the number by 1 and displaying its value until the value is no longer less than 10.
using System; namespace MyApp { class MainClass { public static void Main (string[] args) { for (int i = 0; i < 10; i++) { Console.WriteLine (i); } } } }
And another example shown below will repeat the word “Hello” 10 times.
using System; namespace MyApp { class MainClass { public static void Main (string[] args) { for (int i = 0; i < 10; i++) { Console.WriteLine ("Hello"); } } } }