Loops

Overview

  • While loop
  • For loop
  • Nested loops
  • Breaking out of loops

Why loops?

  • Loops are useful when you need to repeat a block of code multiple times and to avoid code like this:
    Console.WriteLine(count);
    ++count;
    Console.WriteLine(count);
    ++count;
    Console.WriteLine(count);
    // Yuck! Nobody wants to see this.
    
  • Loops can also be used for iterating through arrays and lists (more on those later)

while loop

  • A while loop keeps executing its code block as long as the condition in its statement is true:
    int count = 0;
    while(count < 4)
    {
      Console.WriteLine(count);
      ++count;
    }
    // Outputs '0', '1', '2' and '3'
    

do...while loop

  • do...while works the same way as while, but there's a key difference:
  • The code is executed at least once and the condition is checked at the end:
    int count = 0;
    do
    {
      Console.WriteLine(count);
      ++count;
    } while (count < 4);
    // Outputs '0', '1', '2' and '3'
    

for loop

  • for loops are used when the number of iterations is predefined
  • for loop is initialized in three steps:
    for (<initial value>; <condition>; <increment>)
    {
      /* Code to be executed */
    }
    
  • The initial value is set before the first iteration
  • The condition is checked before each iteration
  • The increment is executed after each iteration

For loop: An example

See the following two examples:

for (int i = 0; i < 4; ++i)
{
  Console.WriteLine
    ("Current: " + i);
}

/* Outputs
Current: 0
Current: 1
Current: 2
Current: 3
*/
for (int i = 8; i > 0; i -= 2)
{
  Console.WriteLine
    ("Current: " + i);
}

/* Outputs
Current: 8
Current: 6
Current: 4
Current: 2
*/

We start from zero int i = 0

print the current value

add one ++i

until the value is no longer under four
i < 4.

for (int i = 0; i < 4; ++i)
{
  Console.WriteLine
    ("Current: " + i);
}

We start from eight int i = 8

print the current value

remove two i -= 2

until the value is no longer over zero
i >

for (int i = 8; i > 0; i -= 2)
{
  Console.WriteLine
    ("Current: " + i);
}

Nested Loops

Nothing prevents you from using a loop inside another loop:

int columns = 3;
int rows = 4;
for (int i = 0; i < columns; ++i)
{
  for (int j = 0; j < rows; ++j)
  {
    // Console.Write doesn't add a linebreak after printout
    Console.Write(
      "(" + j.ToString() + "," + i.ToString() + ")"
    );
  }
  Console.WriteLine("");
}

Breaking out of loops with break

  • To stop the execution of a loop before its end condition is met, use the break keyword:
    int i = 0;
    while(true)
    {
      ++i;
      if(i > 3)
      break;
    }
    // i is now 4
    

Skipping ahead with continue

  • To skip the current iteration, use the continue keyword
    int i = 0;
    while(i < 10)
    {
      ++i;
      if (i % 2 == 0)
      continue;
      Console.WriteLine(i);
    }
    // Prints every odd number from 1 to 10
    

Exercise 1: The main loop

At the heart of every program that doesn't quit right away, there is something called the main loop

  1. Create a console application that keeps asking the user for input until the user inputs quit.
  2. Expand the program so that if the user inputs help, a help screen appears that explains what both quit and help commands do (See next image).

Exercise 2: Prime numbers

A Prime number is a natural number greater than 1 that is not a product of two natural numbers (so it cannot be divided into a whole number).

Create a console application which prints all the prime numbers between 0 and 40.

Assignments

Assignments about this topic can be found here