# Data input and datatypes

(data-input-on-the-console)=
## Data input on the console

`Console.ReadLine()`

We read instead of write as we did in `Console.WriteLine()`.

Try the following:

```cs
Console.WriteLine("Enter your message and then press Enter:");
var line = Console.ReadLine();
Console.WriteLine($"Your message has {line.Length} characters.");
```

## Data types

A computer works with zeroes and ones. These can be interpreted in different ways:

For example, *0110*:

1. four Boolean values (a Boolean can be *true* or *false*): false, true, true, false.
2. an integer: *6*
3. a floating point number: $1 \cdot 2^{-2} = 0.25$ (its decimal dot can *float* to the right). In this example the dot is shifted two times to the right.
4. a decimal number: *1.2* if we set the decimal dot in the middle
5. as a letter; `0110` binary corresponds to 6 in decimal, so sixth letter: *F*
6. as two letters; second (`01`) and third (`10`) letters in sequence: *BC*

Note that C# does not have a built-in type for four bits, so these are just example interpretations.

Some C# types that are similar to the interpretations above:
1. an array of `bool`s
2. [`int` until ~2 billion, `long` much larger](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types)
3. `decimal` (more precise version of `float`)
4. `decimal` (compared to `float` and `decimal` can represent monetary values exactly)
5. `char`
6. `string`

:::{tip}
Use `decimal` for financial and monetary numbers and `decimal` for all other decimal numbers.
:::

:::{card} Question to ponder
Select datatypes for the following variables:

- human height in meters
- number of people in a city
- door is open or not
- price of a product in EUR
- capacity of a modern hard disk in bytes
- gender: divers, female, male <!--enum but we did not introduce. We could also use an int-->
:::

## Using `var`

Instead of writing the datatype explicitly, we can simply write `var` for convenience — but only if it is obvious from the context, which datatype the variable has:

```cs
var age = 0;  // int
var altitude = 0.0;  // decimal
var score = age + altitude; // decimal
var name = "Su";

var numberOfUsers;  // ❌ datatype is not clear
```

:::{note}
Rider will convert statements such as following automatically
```cs
int i = 0;
```
to:
```
var i = 0;
```

:::


(arguments-and-return-value-in-functions)=
## Arguments and return value in functions

These act like input and output to a function.

:::{mermaid} ../img/function-input-output.mmd
:::

Functions can have zero, one or many *arguments* and one *return value*. Usually arguments are used as input and the return value as output, but it is also possible to input *addresses* instead of *values*. If we input addresses, then a function can use them to output values.

Examples:

:::{list-table}
:header-rows: 1

* - function
  - argument/s
  - return value
* - `Console.WriteLine("Hej Geko 👋");`{l=csharp}
  - `"Hej Geko 👋"`: string
  - none
* - `Console.ReadLine();`{l=csharp}
  - none
  - read line: string
* - `Convert.ToString(4.2);`{l=csharp}
  - `4.2`: a double
  - `"4.2"`: string
* - `decimal.TryParse("45.67", parsedDecimal)`{l=cs}
  - `"45.67"`: string

    `parsedDecimal`: variable which the parsed number written to
  - true if parsing was possible; else false.
:::

If we use a function in a wrong way, we get an error:

```cs
Console.ReadLine(4);
```

Output:
```text
Program.cs(1, 9): [CS1501] No overload for method 'ReadLine' takes 1 arguments
```

Fortunately, our IDE helps us with obvious errors:

![](../img/ide-hovered-over-an-error-show-error-message.png)

(conversion-between-datatypes)=
## Conversion between datatypes

When we get keyboard input, this is usually a string. To do arithmetic, we need to convert strings to numerical datatypes.

When we want to output data to the user, we need to convert numerical datatypes to strings again.

```{literalinclude} ../code/conversion-between-datatypes.cs
:language: cs
```

:::{card} Question to ponder
Why do we use strings and numeric datatypes? Can't we just use only strings or numeric datatypes?
:::

(math-expressions)=
## Math expressions

```csharp
int a = 5;
int b = 2;
int sum      = a + b;        // 7
int diff     = a - b;        // 3
int product  = a * b;        // 10
int quotient = a / b;        // 2
int remainder= a % b;        // 1

decimal x = 5.0;
decimal y = 2.0;
decimal div = x / y;         // 2.5

// Exponentiation and root
decimal power = Math.Pow(3, 4);   // 3⁴ = 81
decimal sqrt  = Math.Sqrt(16);    // 4

// Trigonometric functions (angles in radians)
decimal angle = Math.PI / 4;      // 45°
decimal sin   = Math.Sin(angle);  // 0.7071...
decimal cos   = Math.Cos(angle);  // 0.7071...

// Rounding
decimal raw   = 3.14159;
decimal round = Math.Round(raw, 2); // 3.14
```

<!--
Convert the following to an activity

you want to create a visualization of where the robot arm moves if it should rotate around a point 30 degrees. We need a trigonometric function-->

(operator-precedence)=
## Operator precedence

:::{wpd} Order of operations
Collections of conventions about which arithmetic operations to perform first
:::

E.g., $4 + 5 \cdot 2 \ne (4 + 5) \cdot 2 $, but $4+(5 \cdot 2)$.

Precedence:
1. parentheses
1. modulo, multiplication, division
1. addition, subtraction

## Using variables and constants

```cs
// First define a variable
int age = 30;

// Then use it (`age`)
if (age > 30)
  Console.WriteLine("Crisis?")

// Constants 
// Convention: begin with a CAPITAL letter
const decimal Pi = 3.1415926535;
```

We don't have to use `const` for functionality, but we humans make mistakes and this extra information lowers the chance of a mistake later. The compiler will warn us if we try to change the variable.

## Program structure

This time you will write a program from scratch. This is the main structure:
```cs
// 1. Libraries, e.g., `using System.Text.Json` 
// We don't have to use any right now, however.

// 2. Variable declarations
const int threshold = 20;

// 3. Logic
Console.Write("Enter temperature: ");
decimal.TryParse(Console.ReadLine(), out var userInput);

if (userInput > threshold)
    Console.WriteLine("No need for the heater.");
else
    Console.WriteLine("Turn on the heater.");
```

## Coming back to the problem

:::{activity}
:label: conveyor-belt-capacity-check-try-again
We come back to {ref}`conveyor-belt-capacity-check-intro`.

Create an empty project called `ConveyorBeltCapacityCheck` that solves this problem.

Put your flowchart from {ref}`conveyor-belt-capacity-check-flowchart`, because you will upload your project to a code forge and submit it later as an assignment.

Steps:
- 10 min [pair programming](project:#tapps)
- one student presents their (half-)solution
:::

## Appendix

- [C# types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types)
- [Integral numeric types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types)
- [Different versions of `WriteLine`](https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline)
- [How to convert a string to a number](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number)
