For Loops

For loops are used when we know exactly how many times we want to execute the loop.

For loop example

The following is taken from a GCSE exam paper. It shows pseudocode for a count controlled loop. The for loop will run exactly 10 times for the values 1 to 10. Each time the code loops it will print the value of i. This means that the code will print the numbers 1 to 10.

Pseudocode

text

C# code

In C# inside the round brackets:

  • create the local variable i and set to 1
  • write the test to decide if the loop will continue (as long as i is less than or equal to 10).
  • set the step value. In this case i++ will add one each time the loop repeats.
for (int i = 1; i <= 10; i++)
{
    Console.WriteLine(i);
}

Want to know more?

Find out more on W3Schools by clicking here.


Getting out of a loop... Break and Continue

Most loops include many lines of code which need to be executed inside the loop. Find out more about break and continue on W3Schools here.