---
marp: true
paginate: true
math: mathjax
theme: buutti
title: 4. Loops
---

# Loops

<!-- headingDivider: 5 -->
<!-- class: invert -->

## 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:
  ```csharp
  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`:
  ```csharp
  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***:
  ```csharp
  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:
  ```csharp
  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:

<div class='columns' markdown='1'>
<div markdown='1'>

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

/* Outputs
Current: 0
Current: 1
Current: 2
Current: 3
*/
```

</div>
<div markdown='1'>

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

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

</div>
</div>

---


<div class='columns' markdown='1'>
<div markdown='1'>

We start from zero `int i = 0`

print the current value

add one `++i`

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

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

</div>
<div markdown='1'>

We start from eight `int i = 8`

print the current value

remove two `i -= 2`

until the value is no longer over zero
`i >`

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

</div>
</div>

## Nested Loops

Nothing prevents you from using a loop inside another loop:

<div class='columns' style='grid-template-columns: 3fr 1fr;' markdown='1'>
<div markdown='1'>

```csharp
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("");
}
```

</div>
<div markdown='1'>

![](imgs/4%20Loops_1.png)

</div>
</div>

## Breaking out of loops with `break`

* To stop the execution of a loop before its end condition is met, use the  `break` keyword:
  ```csharp
  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
  ```csharp
  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
<!--_class: "exercise invert" -->

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).

---
<!--_class: "exercise invert" -->

![w:1200px](imgs/4%20Loops_2.png)

## Exercise 2: Prime numbers
<!--_class: "exercise invert" -->

A [Prime number](https://en.wikipedia.org/wiki/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](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/4.%20Loops)

