Iteration (Weeks 7 to 10)

Learning Objectives

  • Understand the need for iteration in code.
  • Write a basic “for” loop.
  • Look at a “do while” loop.
  • Compare with a “while do” loop
  • The best situation for a given loop

Learning Outcomes.  You –

Must understand the purposes and  recognise the main types of iteration (U/E)

Should Solve problems using for and while loops. (D/C)

Could Choose the most appropriate type of loop for a given situation (B/A)

Keywords

Words to learn: Loop, iterate, for, while, boolean test.

 

Starter

This link should give you a tacky “game”.  Run it, and try to complete the challenge in the fewest possible moves.

Main

Simple “for” loop

By using a for loop, you can run a statement or a block of statements repeatedly until a specified expression evaluates to false. This kind of loop is useful for iterating over arrays and for other applications in which you know in advance how many times you want the loop to iterate.

static void Main(string[] args)

{
for(int i = 0; i<5; i++)

{

Console.WriteLine(i)

}

Console.ReadKey();
}

Simple “While” loop

Because the test of the while expression takes place before each execution of the loop, a while loop executes zero or more times. This differs from the do loop, which executes one or more times.

class WhileTest 
{
    static void Main() 
    {
        int n = 1;
        while (n < 6) 
        {
            Console.WriteLine("Current value of n is {0}", n);
            n++;
        }
    }
}

“Do While” loop

The do statement executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The body of the loop must be enclosed in braces, {}, unless it consists of a single statement. In that case, the braces are optional.

In the following example, the do-while loop statements execute as long as the variable x is less than 5.


 int x = 0;
        do 
        {
            Console.WriteLine(x);
            x++;
        } while (x < 5);

Unlike the while statement, a do-while loop is executed one time before the conditional expression is evaluated.

At any point in the do-while block, you can break out of the loop using the break statement. You can step directly to the while expression evaluation statement by using the continue statement. If the while expression evaluates to true, execution continues at the first statement in the loop. If the expression evaluates to false, execution continues at the first statement after the do-while loop.