---
marp: true
paginate: true
math: mathjax
theme: buutti
title: 3. Conditionals
---

# Conditionals

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

## Overview

* Conditionals
* `if` and `else`
* Logical Operators

## Comparison operators

* ***Comparison operators*** are used to compare two variables
  * They return either `true` or `false`
* Two variables of any type can be compared with equality operators
  * Equal to: `a == b`
    * (Do not mix with the assignment operator, see [Lecture 2](2-variables-and-types#assignment-operators)!)
  * Not equal to: `a != b`
* Two ***numbers*** can be further compared with less than/greater than operators: 
  * Less than: `a < b`
  * Less than or equal: `a <= b`
  * Greater than: `a > b`
  * Greater than or equal: `a >= b`

<!-- | Comparison               | Syntax   |
|:-------------------------|:---------|
| Less than                | `a < b`  |
| Less than or equal to    | `a <= b` |
| Greater than             | `a > b`  |
| Greater than or equal to | `a >= b` |
| Equal to                 | `a == b` |
| Not equal to             | `a != b` | -->

### `bool` data type

* As shown in [Lecture 2](2-variables-and-types#primitive-data-types), `bool` is a data type for storing truth values `true` or `false`
* Because conditionals return `true` or `false`, the result can be stored in a variable
  ```csharp
  int a = 4;
  int b = 3;
  bool areEqual = a == b;   // outputs False
  bool biggerOrNot = a > b; // outputs True
  ```
* Useful for making multiple comparisons at once

## `if`, `else if` and `else` statements

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

* `if` checks truthfulness of a given statement
* If it results in `false`, we can check if another condition is met with `else if`
* Multiple `else if` can be chained indefinitely
* If no statement returns `true`, the `else` block is executed
* The statements are checked in order, and the first `true` condition is executed 
  * No other block is executed
* (You can also have just `if` and `else` without the `else if`, or just a single `if`.)

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

```csharp
int a = 2
if (a > 4)
{
  // do something
}
else if (a < 2)
{
  // do something else
}
else if (a < 3)
{
  // do something else
}
else
{
  // a is 4??
}
```

</div>
</div>


### Conditionals: An example

```csharp
double temperatureInOulu = 2.3;
double temperatureInIvalo = -10.9;
if (temperatureInOulu > temperatureInIvalo)
{
  Console.WriteLine("Oulu is warmer than Ivalo");
}
else if (temperatureInOulu < temperatureInIvalo)
{
  Console.WriteLine("Ivalo is warmer than Oulu");
}
else
{
  Console.WriteLine
    ("Oulu and Ivalo have the same temperature");
}
```

This outputs `Oulu is warmer than Ivalo`.

## Not operator `!`

* The `!` ("not") operator flips the boolean value.
```csharp
Console.WriteLine(!true);     // Outputs false
bool itsColdOutside = true;
if (!itsColdOutside)          // same as checking if (itsColdOutside == false)
{
  Console.WriteLine("It's warm outside.");
}
```

## The `switch` statement

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

* The `switch` statement compares the given expression (in this example, the `path` variable) with the value of each  `case`
* Only the matching code is executed
* If no match is found, the default code block is executed
* This example outputs `Here's the catalogue!`
* `break` ends each case (the code will not compile if omitted!)

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

```csharp
string path = "/browse";

switch (path)
{
  case "/browse":
    Console.WriteLine("Here's the catalogue!");
    break;
  case "/contact":
    Console.WriteLine("Here's our contact info.");
    break;
  default:
    Console.WriteLine("Given path doesn't exist!");
    break;
}
```

</div>
</div>

## Scope of Variables

* Variables declared inside of blocks `{}` are ***local*** to that ***scope***; they are only accessible inside of that block
  ```csharp
  if (true)
  {
    int b = 1;        // b is only accessible in this block
    b = 2;            // This works
  }

  b = 3;              // This throws an error
  ```
* Similarly, classes are only defined inside their `namespace`, and have to be imported to be accessible elsewhere
* ***Note:*** Some languages have `global` variables that are accessible everywhere — as an object-oriented language, C# doesn't have such feature.

## Logical Operators

* `&&`, `||` and `!` are the logical AND, OR and NOT operators
* These are useful when writing complex `if` statements

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

```csharp
int a = 1;
int b = 3;
int c = 5;
if (a < 10)
{
  if (b < 10)
  {
    if (c < 10)
    {
      Console.WriteLine
        ("All are smaller than 10!")
    }
  }
}
```

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

```csharp
int a = 1;
int b = 3;
int c = 5;
if (a < 10 && b < 10 && c < 10)
{
  Console.WriteLine
    ("All are smaller than 10!")
}
```
* Same functionality achieved in fewer lines!

</div>
</div>

### Common logical operators

| Operator | Name | Usage      | Description                                                                              |
|:---------|:-----|:-----------|:-----------------------------------------------------------------------------------------|
| `&&`     | AND  | `a && b`   | Returns `true` if *__both__* variables are true.<br>`b` is not evaluated if `a == false`.       |
| `\|\|`   | OR   | `a \|\| b` | Returns `true` if *__one or both__* variables are true.<br>`b` is not evaluated if `a == true`. |
| `!`      | NOT  | `!a`       | Negates the boolean value.<br>(`true` becomes `false` and vice versa).                           |

### Less common logical operators

| Operator | Name        | Usage    | Description                                                                              |
|:---------|:------------|:---------|:-----------------------------------------------------------------------------------------|
| `^`      | XOR         | `a ^ b` &nbsp; | Exclusive OR ("*joko tai*"): returns `true` if *__only either of__* `a` or `b` are `true`, but not both!              |
| `&`      | Logical AND | `a & b`  | Returns `true` if __both__ variables are `true`.<br>Both variables are always evaluated.        |
| `\|`     | Logical OR  | `a \| b` | Returns `true` if __one or both__ variables are `true`.<br>Both variables are always evaluated. |

### Logical operators: An Example


```csharp
int uppercaseLetters = 2;
uppercaseLetters += 4;          // is now 6

int specialCharacters = 2;
specialCharacters *= 2;         // is now 4

if (uppercaseLetters >= 6 && specialCharacters >= 2)
{
  Console.WriteLine("Strong password!");
}
else
{
  Console.WriteLine("Weak password...");
}
```
This outputs `Strong password!`

## Extra: Single statement `if`
<!-- _class: "extra invert" -->

* If a code block following a statement only has one line of code, it is possible to write the block ***without*** curly brackets:
  ```csharp
  int baa = 49;
  if (baa > 20)
    Console.WriteLine("Baa");
  else
    Console.WriteLine("Not baa!");
  if (baa > 20) Console.WriteLine("Baa");
  else Console.WriteLine("Not baa!");
  ```
* You may encounter code like this — however, we highly recommend to refrain from using this syntax as it is highly prone to [errors](https://www.leadingagile.com/2018/01/the-goto-fail-bug-as-a-coaching-tool/).
  * Can you guess how this syntax can lead to bugs?

## Exercise 1
<!--_class: "exercise invert" -->

1) Create a console application that asks the user which weekday it is and assigns the answer to a string variable.
2) Using a switch-case expression, calculate the days remaining until next Monday.
3) If the result is more than 3, print `Have a nice week!`. Otherwise, print `Have a nice weekend!`.

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

1) Create a console application that lets the user input a note as a string.
2) If the length of the note is less than 30, the program prints the current time and the note separated by a tab. Otherwise, the date and the note are printed to a separate line.

***Tip:*** Use `DateTime.Now.ToString()` for current time. Use `.Length` after your message variable to get the length of the message.


## Reading

Basics covering the syntax in C# are covered here:

* [Learn .NET: C# Documentation](https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/)
* [Tutorialspoint: C# tutorial](https://www.tutorialspoint.com/csharp/index.htm)
* [W3Schools: C# tutorial](https://www.w3schools.com/cs/default.asp)

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

[Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/3.%20Conditionals)

