Loops are useful when you need to repeat a block of code multiple times and to avoid code like this:
<!-- headingDivider: 5 -->
<!-- class: invert -->
Console.WriteLine(count);
## Overview
++count;
* While loop
Console.WriteLine(count);
* For loop
* Nested loops
++count;
* Breaking out of loops
Console.WriteLine(count);
## Why loops?
// Yuck! Nobody wants to see this.
* Loops are useful when you need to repeat a block of code multiple times and to avoid code like this:
```csharp
Loops can also be used for iterating through arrays and lists (more on those later)
Console.WriteLine(count);
++count;
# while Loop
Console.WriteLine(count);
++count;
_while_ loop keeps executing its code block as long as the condition in its statement is true:
Console.WriteLine(count);
// Yuck! Nobody wants to see this.
int count = 0;
```
* Loops can also be used for iterating through arrays and lists (more on those later)
while(count <4)
## `while` loop
{
* A `while` loop keeps executing its code block as long as the condition in its statement is `true`:
Console.WriteLine(count);
```csharp
int count = 0;
++count;
while(count <4)
{
}
Console.WriteLine(count);
++count;
// Outputs '0', '1', '2' and '3'
}
// 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:
## `do...while` loop
int count = 0;
* `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***:
do
```csharp
int count = 0;
{
do
{
Console.WriteLine(count);
Console.WriteLine(count);
++count;
++count;
} while (count <4);
// Outputs '0', '1', '2' and '3'
} while (count <4);
```
// Outputs '0', '1', '2' and '3'
## `for` loop
# for Loop
* `for` loops are used when the number of iterations is predefined
* `for` loop is initialized in three steps:
_for _ loops are used when the number of iterations are predefined
```csharp
for (<initialvalue>; <condition>; <increment>)
for loop executes in three inherent steps:
{
/* Code to be executed */
for (/*initial value*/;/*condition*/;/*increment*/)
}
```
{
* The ***initial value*** is set before the first iteration
* The ***condition*** is checked before each iteration
/* Code to be executed */
* The ***increment*** is executed after each iteration
}
## For loop: An example
The initial value is set before the first iteration. The condition is checked before each iteration, and the increment is executed after each iteration.
See the following two examples:
# for Loop (continued)
<divclass='columns'markdown='1'>
<divmarkdown='1'>
Try to understand the following two examples:
```csharp
for (int i = 0; i <4;++i)
for (int i = 0; i <4;++i)
{
{
Console.WriteLine
Console.WriteLine
("Current: " + i);
("Current: " + i);
}
}
/* Outputs
/* Outputs
Current: 0
Current: 0
Current: 1
Current: 1
Current: 2
Current: 2
Current: 3
Current: 3
*/
*/
```
for (int i = 8; i > 0; i -= 2)
</div>
<divmarkdown='1'>
```csharp
for (int i = 8; i > 0; i -= 2)
{
{
Console.WriteLine
Console.WriteLine
("Current: " + i);
("Current: " + i);
}
}
/* Outputs
/* Outputs
Current: 8
Current: 8
Current: 6
Current: 6
Current: 4
Current: 4
Current: 2
Current: 2
*/
*/
```
We start from zero, print the current value and add one until the value is no longer under four.
</div>
</div>
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)
{
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.WriteLine
// Console.Write doesn't add a line break after printout
// Console.Write doesn't add a linebreak after printout
if (i % 2 == 0)
Console.Write(
"(" + j.ToString() + "," + i.ToString() + ")"
continue;
);
}
Console.WriteLine(i);
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)
[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>];
<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="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">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 .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="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>
<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>
<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)
[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)