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
_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 it executes the code at least once and checks the condition 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 are predefined
for loop executes in three inherent 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, and the increment is executed after each iteration.
# for Loop (continued)
Try to understand the following two examples:
<!-- 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 (<initialvalue>; <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:
<divclass='columns'markdown='1'>
<divmarkdown='1'>
```csharp
for (int i = 0; i <4;++i)
{
Console.WriteLine
("Current: " + i);
Console.WriteLine
("Current: " + i);
}
/* Outputs
Current: 0
Current: 1
Current: 2
Current: 3
*/
```
for (int i = 8; i > 0; i -= 2)
</div>
<divmarkdown='1'>
```csharp
for (int i = 8; i > 0; i -= 2)
{
Console.WriteLine
("Current: " + i);
Console.WriteLine
("Current: " + i);
}
/* Outputs
Current: 8
Current: 6
Current: 4
Current: 2
*/
```
We start from zero, print the current value and add one until the value is no longer under four.
We start from eight, print the current value and remove two until the value is no longer larger than zero.
for (int i = 8; i > 0; i -= 2)
{
</div>
</div>
Console.WriteLine
("Current: " + i);
}
for (int i = 0; i <4;++i)
{
Console.WriteLine
("Current: " + i);
}
# Nested Loops
---
Nothing prevents you from using a loop inside another loop:
int columns = 3;
<divclass='columns'markdown='1'>
<divmarkdown='1'>
int rows = 4;
We start from zero `int i = 0`
for (int i = 0; i <columns;++i)
print the current value
{
add one `++i`
for (int j = 0; j <rows;++j)
until the value is no longer under four
`i < 4`.
```csharp
for (int i = 0; i <4;++i)
{
// Console.Write doesn't add a line break after printout
// Console.Write doesn't add a linebreak after printout
Console.Write(
"(" + j.ToString() + "," + i.ToString() + ")"
);
}
Console.WriteLine("");
}
```
// Prints every odd number from 1 to 10
</div>
<divmarkdown='1'>
# Exercise 1: The Main Loop
At the heart of every dynamic program, there is something called the _event loop _ a.k.a the _main loop. _ Create a console application which keeps asking the user for an input, until the user inputs "quit".

Expand the program so that if the user inputs "help", a dialog shows up which shows the command and explanation for the command for both quit and help commands.
</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" -->
# Exercise 2: Prime Numbers

Prime number is a number greater than 1 that is not a product of two small numbers, i.e. cannot be divided into a whole number. (Wikipedia: [https://en.wikipedia.org/wiki/Prime\_number](https://en.wikipedia.org/wiki/Prime_number) )
## Exercise 2: Prime numbers
<!--_class: "exercise invert" -->
Create a console application which prints all the prime numbers between 0 .. 40
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
[Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/4.%20Loops)
<lidata-marpit-fragment="1"><em><strong>Initialize</strong></em> an array with a length of 3 using the following syntax:<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp"><spanclass="hljs-built_in">int</span>[] userIds = <spanclass="hljs-keyword">new</span><spanclass="hljs-built_in">int</span>[<spanclass="hljs-number">3</span>];
@ -50,7 +50,7 @@
<lidata-marpit-fragment="3">Indexing starts from 0, so the above line assigns a value of <code>104</code> to the <em><strong>first</strong></em> element of the array</li>
<lidata-marpit-fragment="1">You can also create an array and instantly populate it with values with one statement:<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp"><spanclass="hljs-built_in">string</span>[] names = <spanclass="hljs-keyword">new</span><spanclass="hljs-built_in">string</span>[<spanclass="hljs-number">3</span>] { <spanclass="hljs-string">"Johannes"</span>, <spanclass="hljs-string">"Rene"</span>, <spanclass="hljs-string">"Ville"</span> };
<lidata-marpit-fragment="1">The .NET Framework Library <ahref="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic?view=net-9.0"><code>System.Collections.Generic</code></a> offers another structure to contain multiple variables: the <ahref="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-9.0">List</a> class</li>
<lidata-marpit-fragment="1">The memory allocation of an array is <em><strong>static</strong></em> a.k.a. fixed, but list memory is <em><strong>dynamic</strong></em></li>
<lidata-marpit-fragment="5"><em><strong>Note</strong></em>: you can use the <code>int.Parse()</code> method to parse the user input string to an integer</li>
<p><ahref="https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/5.%20Arrays%20&%20Lists">Assignments about this topic can be found here</a></p>
[Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/5.%20Arrays%20&%20Lists)